﻿Imports SAP.Connector
Imports System.Globalization

Partial Public Class frm_Booking
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData()
    Dim clsFc As New ClassFunction()
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
        lbPage.Text = "BOOKING"
        If Not IsPostBack Then

            Session("MAT_USE") = ""
            Session("Value") = Nothing
            Session("Q88") = CreateFileDataTable()
            Session("StandardTimePlus") = 0
            ViewState("Status") = ""
            ViewState("EditBooking") = ""
            ViewState("BookingDataset") = Nothing
            Dim ClientName As String = Request.ServerVariables("http_user_agent")
            If (ClientName.Split("(")(1).Split(";")(0) = "compatible") Then
                'สำหรับเครื่องที่เข้าระบบผ่าน NOTEBOOK
                panelGridItem.Width = 900
            Else
                'สำหรับเครื่องที่เข้าระบบผ่าน iPHONE
                panelGridItem.ScrollBars = ScrollBars.None
            End If

            Session("Operation") = Nothing
            ShowPanelForRole()
            ViewState("Load") = "Not"
            Timer1_Tick(sender, e)
            btnCancel.Attributes.Add("OnClick", "javascript: return confirm('คุณต้องการที่จะย้อนกลับหรือไม่')")
            btnUpdate.Attributes.Add("OnClick", "javascript: return confirm('คุณต้องการทำการ Update ข้อมูล?')")
            txtBookingVPS.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchVPS.ClientID + "')")
            txtAGENTVPS.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchVPS.ClientID + "')")
            txtShipVPS.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchVPS.ClientID + "')")
            txtProductSearch.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchVPS.ClientID + "')")
            btnSearchVPS.Focus()
        Else
            Dim s As String = postBackClick.Value
            'Session("Q88") = CreateFileDataTable()
            ' ShowPanelForRole()
            gridItem.DataSource = ViewState("Booking")
            gridItem.DataBind()
        End If
    End Sub

    Private Sub ShowPanelForRole()
        Dim ds As DataSet
        Dim conditionFirst As Boolean = True
        If (Session("Role") & "" = "00002") Or (Session("Role") & "" = "00007") Then
            'ลูกค้า
            ds = clsGet.Get_Booking(CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_Name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no") & "", "", "", False, "", "", "", "'CV','CC','CM','CR','CA'", "", "A", "", "", txtProductSearch.Text)
            If (ds.Tables(0).Rows.Count = 0) Then
                'ไม่มีรายการ Booking คงค้าง
                PanelBooking.Visible = True
                PanelBookingItem.Visible = False
                PanelDetail.Visible = False
                btnCompute.Visible = False
                btnCancelBooking.Visible = False
                conditionFirst = False
                ClearData()
            Else
                'รายการ Booking
                ds.Tables(0).Columns.Add("Lay", GetType(String))
                ds.AcceptChanges()
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    ds.Tables(0).Rows(i).Item("Lay") = CDate(ds.Tables(0).Rows(i).Item("Date_From")).ToString("yyyyMMdd")
                    ds.Tables(0).AcceptChanges()
                Next
                Dim dsView As DataView = ds.Tables(0).DefaultView
                dsView.Sort = " Lay DESC"
                ds = New DataSet
                ds.Tables.Add(clsGet.ConvertDataViewToDataSet(dsView).Copy())

                PanelBookingItem.Visible = True
                PanelBooking.Visible = False
                ViewState("Booking") = ds
                gridItem.DataSource = ViewState("Booking")
                gridItem.DataBind()
            End If
        Else
            'สิทธิ์ อื่นๆที่ไม่ใช่ลูกค้า
            Try
                If (Session("Role") & "" = "00001") Then
                    ds = clsGet.Get_Booking(CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_Name"), "", "", "", True, "", "", "", "'CV','CC','CM','CR','CA'", "", "A", "", "", txtProductSearch.Text)
                Else
                    ds = clsGet.Get_Booking(CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_Name"), "", "", "", True, "", "", "", "'CV','CC','CM','CR','CA'", "", "A", "", "", txtProductSearch.Text)
                End If
            Catch ex As Exception
                Response.Redirect("~/Form/Logon.aspx")
            End Try
           

            If (ds.Tables(0).Rows.Count > 0) Then

                ds.Tables(0).Columns.Add("Lay", GetType(String))
                ds.AcceptChanges()
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    ds.Tables(0).Rows(i).Item("Lay") = CDate(ds.Tables(0).Rows(i).Item("Date_From")).ToString("yyyyMMdd")
                    ds.Tables(0).AcceptChanges()
                Next
                Dim dsView As DataView = ds.Tables(0).DefaultView
                dsView.Sort = " Lay DESC"
                ds = New DataSet
                ds.Tables.Add(clsGet.ConvertDataViewToDataSet(dsView).Copy)

                PanelBookingItem.Visible = True
                PanelBooking.Visible = False
                ViewState("Booking") = ds
                gridItem.DataSource = ViewState("Booking")
                gridItem.DataBind()
            Else
                PanelBooking.Visible = True
                PanelBookingItem.Visible = False
                PanelDetail.Visible = False
                'PanelCustomerID.Visible = True
                btnCompute.Visible = False
                btnCancelBooking.Visible = False
                conditionFirst = False
                ClearData()
            End If
        End If
        txtName.Text = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name")
        hdfUsername.Value = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name")
        If (Session("Role") <> "00002") Then
            ComputeTariff.Visible = True
            rowGridTariff.Visible = False
            If (conditionFirst) Then
                btnCompute.Visible = False
            End If
        Else
            ComputeTariff.Visible = False
            rowGridTariff.Visible = False
            If (conditionFirst) Then
                btnCompute.Visible = True
            End If
        End If
        Session("Product_popup") = CreateDatasetProduct()
        gridProduct.DataSource = Session("Product_popup")
        gridProduct.DataBind()
    End Sub

    Private Sub LoadDefault_MAT(ByVal National As String, ByVal TypeBuy As String, ByVal Load As String, ByVal Disch As String, ByVal MaterialB As String, ByVal VesselNational As String)
        Session("MAT_USE") = clsGet.Get_MeterailDefault("", True, "", radioPort.SelectedValue, National, TypeBuy, Load, Disch, MaterialB, VesselNational, "")
        gridTariff.PageIndex = 0
        gridTariff.DataSource = Session("MAT_USE")
        gridTariff.DataBind()
    End Sub

    Private Sub ReadOnlyControl()
        txtDate.ReadOnly = True
        txtDateTo.ReadOnly = True
        raioType.Enabled = False
        radioPort.Enabled = False
        btnTariff.Enabled = False
        ImgDate.Enabled = False
        ImgDateTo.Enabled = False
        txtVessel.ReadOnly = True
    End Sub

    Private Sub btnNew_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNew.Click
        btnCompute.Visible = True
        btnUpdate.Visible = False
        PanelBooking.Visible = True
        PanelBookingItem.Visible = False
        PanelDetail.Visible = False
        radioPort.ClearSelection()
        radioPort.Enabled = True
        txtAgent.Enabled = True
        txtAgent.Text = String.Empty
        btnProduct.Enabled = True
        btnProduct.Visible = True
        txtid.Enabled = True
        txtVessel.Enabled = True
        txtVesselOUT.Enabled = True
        ddlNation.Enabled = True
        txtLOA.Enabled = True
        txtDraft.Enabled = True
        txtDWT.Enabled = True
        txtGRT.Enabled = True
        btnSearchOUT.Visible = True
        btnSearch.Visible = True
        btnAddNew_Service.Visible = False
        rowDetailAll.Visible = False
        PanelDetail.Visible = False
        PanelVessel.Visible = False
        PanelVEHICLE_IN_DETAIL.Visible = False
        ViewState("Status") = ""
        Session("Product_popup") = CreateDatasetProduct()
        ViewState("EditBooking") = ""
        Session("Lay_Time") = "0"

        Session("MAT_USE") = ""
        Session("Value") = Nothing
        Session("Q88") = CreateFileDataTable()
        gridfile.DataSource = Session("Q88")
        gridfile.DataBind()
        Session("StandardTimePlus") = 0
        ViewState("Status") = ""
        ViewState("EditBooking") = ""
        Session("Operation") = Nothing

        gridProduct.DataSource = Session("Product_popup")
        gridProduct.DataBind()
        txtDate.Enabled = True
        ImgDate.Enabled = True
        txtDateTo.Enabled = True
        ImgDateTo.Enabled = True
        ImgDateBooking.Enabled = True
        txtDateBooking.Enabled = True
        txtTimeBooking.Enabled = True
        ClearData()
        txtName.Text = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name")
        hdfUsername.Value = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name")
        btnCompute.Visible = False
        btnCancelBooking.Visible = False
        If (Session("Role") <> "00002") Then
            ComputeTariff.Visible = True
            rowGridTariff.Visible = False
        Else
            ComputeTariff.Visible = False
            rowGridTariff.Visible = False
        End If
    End Sub
    Private Sub ClearData()
        radioDemurrage.ClearSelection()
        radioDemurrage.SelectedValue = "N"
        rowLaytime.Visible = False
        txtid.Text = String.Empty
        txtid.Enabled = True
        txtWater.Text = "0"
        txtElectricity.Text = "0"
        txtDemurrage.Text = "0"
        radioVehicle.ClearSelection()
        radioVehicle.Enabled = True
        radioVehicle.SelectedValue = "0"
        PanelVEHICLE_IN.Visible = True
        PanelVEHICLE_OUT.Visible = False
        PanelVEHICLE_IN_DETAIL.Visible = False
        ComputeTariff.Visible = False
        txtVessel.Text = String.Empty
        txtVessel.Enabled = True
        txtVesselOUT.Text = String.Empty
        txtDemurrage.Text = "0"
        txtVesselOUT.Enabled = True
        txtLOA.Text = String.Empty
        txtDWT.Text = String.Empty
        txtDraft.Text = String.Empty
        txtGRT.Text = String.Empty
        txtLayTime.Text = "0"
        txtDate.Text = String.Empty
        txtDateTo.Text = String.Empty
        raioType.ClearSelection()
        raioType.SelectedValue = "I"
        rowTypeBuy.Visible = False
        radioTypeBuy.ClearSelection()
        radioPort.ClearSelection()
        txtRemark.Text = String.Empty
        txtDateBooking.Text = String.Empty
        txtTimeBooking.Text = String.Empty
        radioPort.ClearSelection()
        radioPort.Enabled = True
        txtAgent.Text = String.Empty
        txtAgent.Enabled = True
        gridTariff.DataSource = Nothing
        gridTariff.DataBind()
        ViewState("EditBooking") = ""
    End Sub
    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        ClearData()
        ShowPanelForRole()
        ViewState("Load") = "Not"
        Timer1_Tick(sender, e)
    End Sub

    Private Sub SetProductBulk(ByVal dt As DataTable)
        If Not (dt Is Nothing) Then
            For Each dr As DataRow In dt.Rows
                dr.Item("Product_Buyer_no") = dr.Item("Owner_Product_no")
                dr.Item("Product_Buyer_name") = dr.Item("Owner_Product_name")
            Next
            dt.AcceptChanges()
        End If
    End Sub

    Private Sub gridItem_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridItem.RowCommand
       
        Dim comArg As String = e.CommandArgument
        Dim splitComArg As String() = comArg.Split(";")
        Dim Index As Integer = Convert.ToInt32(splitComArg(0))
        If (gridItem.PageIndex <> 0) Then
            Index = Index Mod (gridItem.PageIndex * 10)
        End If
        If e.CommandName = "Edit" Then
            Dim booking_no As String = splitComArg(1)
            GetEditGridItem(booking_no, Index)
        ElseIf e.CommandName = "Detail" Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_IframeDetailPopup').src = '../FormPopup/Detail_VesselBerth_Popup.aspx';", True)
            Session("Booking_no_Detail") = gridItem.DataKeys(Index).Values("Booking_no")
            ModalPopupExtender9.Show()
        End If
    End Sub
    Private Function GetDataFromGridItem(ByVal booking_no As String, ByVal column_name As String) As String
        Dim dsBookingViewState As DataSet = ViewState("BookingDataset") 'ViewState("Booking")
        Dim dtBooking As DataTable = dsBookingViewState.Tables(0)
        ' Dim dtcount As Integer = dtBooking.Rows.Count
        'Dim drSel() As DataRow = dtBooking.Select("Booking_no='" & booking_no & "'")
        Try
            'Return drSel(0)(column_name).ToString()
            Return dtBooking.Rows(0).Item(column_name).ToString()
        Catch ex As Exception
            Return ""
        End Try

        ' Return ""
    End Function
    Private Sub GetEditGridItem(ByVal booking_no As String, ByVal Index As Integer)
        PanelBooking.Visible = True
        PanelBookingItem.Visible = False
        PanelVessel.Visible = True
        lbFT1.Text = "FT"
        lbFT2.Text = "FT"
        ViewState("rowEditIndex") = Index
        ViewState("EditBooking") = booking_no

        Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
        lbPage.Text = "BOOKING No. " + booking_no

        Dim admin As Boolean = True
        If (Session("Role") = "00002") Then
            admin = False
        End If
        Dim usrName, cusNo As String

        usrName = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_Name")
        cusNo = gridItem.DataKeys(Index).Values("Customer_no") & ""
        'gridItem.DataKeys(Index).Values("Customer_no")
        Dim dsBooking As DataSet = clsGet.Get_Booking(CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_Name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no") & "", booking_no, "", admin, "", "", "", "", "", "A", "", "", txtProductSearch.Text)
        ViewState("BookingDataset") = dsBooking
        Dim count As Integer = dsBooking.Tables(0).Rows.Count
        Dim numRow As Integer
        numRow = dsBooking.Tables(0).Rows.Count
        Try
            txtName.Text = dsBooking.Tables(0).Rows(0).Item("Booking_Name")
            hdfUsername.Value = dsBooking.Tables(0).Rows(0).Item("Booking_Code")
        Catch ex As Exception

        End Try

        If (Session("Role") & "" = "00002") Then
            rowGridTariff.Visible = False
        Else
            rowGridTariff.Visible = True
        End If
        btnViewChildBooking.Visible = False
        
        'Dim dtRowsCount As Integer = dtBooking.Rows.Count
        ' Dim bookRef As String = dtBooking.Rows(Index)("parentBookingRef").ToString()
        Dim db As DB_Class = New DB_Class()
        Dim drc As DataRowCollection = db.getTableWhere("Booking", "parentBookingRef='" + booking_no + "'")
        If (drc.Count > 0) Then
            btnViewChildBooking.CommandArgument = Index & ";" & drc(0)("Booking_no")
            btnViewChildBooking.Text = "ดูข้อมูล Child Booking (" & drc(0)("Booking_no") & ")"
            btnViewChildBooking.Visible = True
        End If
        btnCancelBooking.Visible = True
        btnCopyBooking.Visible = True
        btnCompute.Visible = True
        rowCancel.Visible = False
        txtDate.BackColor = Drawing.Color.White
        txtDateTo.BackColor = Drawing.Color.White

        Dim Status As String = GetDataFromGridItem(booking_no, "Status")
        ViewState("ST") = Status 'gridItem.DataKeys(Index).Values("Status") & ""
        If (Status <> "NB") Then 'gridItem.DataKeys(Index).Values("Status") & "" <> "NB"
            ViewState("Status") = "NOT_NEW"
            txtVessel.Enabled = False
            txtVesselOUT.Enabled = False
            btnTariff.Visible = False
            btnSearch.Visible = False
            btnSearchOUT.Visible = False
            radioPort.Enabled = False
            radioVehicle.Enabled = False
        Else
            ViewState("Status") = ""
            txtVessel.Enabled = True
            txtVesselOUT.Enabled = True
            btnTariff.Visible = True
            btnSearch.Visible = True
            btnSearchOUT.Visible = True
            radioPort.Enabled = True
            radioVehicle.Enabled = True
        End If
        btnAddNew_Service.Visible = True
        btnCompute.Text = "แสดงค่าประมาณการ"
        rowDetailAll.Visible = True

        Dim MAgent_no As String = GetDataFromGridItem(booking_no, "MAgent_no")
        If (MAgent_no <> "") Then
            txtid.Text = MAgent_no & "-" & GetDataFromGridItem(booking_no, "MAgent_name") 'gridItem.DataKeys(Index).Values("MAgent_name")
        Else
            txtid.Text = String.Empty
        End If

        Dim SAgent_no As String = GetDataFromGridItem(booking_no, "SAgent_no")
        If (SAgent_no <> "") Then
            txtAgent.Text = SAgent_no & "-" & GetDataFromGridItem(booking_no, "SAgent_name") 'gridItem.DataKeys(Index).Values("SAgent_name")
        Else
            txtAgent.Text = String.Empty
        End If

        radioVehicle.ClearSelection()
        

        Session("MAT_USE") = clsGet.Get_BookingTariff(booking_no, "")
        Session("Product_popup") = clsGet.Get_Booking_Product(booking_no)
        Session("Q88") = clsGet.Get_BookingUpload(booking_no)
        Select Case dsBooking.Tables(0).Rows(0).Item("Status")
            Case "CC"
                lbCancel.Text = "ลูกค้าประสงค์ทำการยกเลิก รอการยืนยันจากทาง VPS<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
                If (dsBooking.Tables(0).Rows(0).Item("Vps_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> VPS รับทราบการขอยกเลิกรายการจองแล้ว"
                    btnCancel.Visible = False
                End If
                If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
                    btnCancel.Visible = False
                End If
            Case "CR"
                lbCancel.Text = "ยกเลิกโดย MRI<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
                btnCancel.Visible = False
                If (dsBooking.Tables(0).Rows(0).Item("Vps_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> VPS รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
                If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
            Case "CM"
                lbCancel.Text = "ยกเลิกโดย Marketing<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
                btnCancel.Visible = False
                If (dsBooking.Tables(0).Rows(0).Item("Vps_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> VPS รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
            Case "CV"
                lbCancel.Text = "ยกเลิกโดย VPS<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
                btnCancel.Visible = False
                If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
            Case "CA"
                lbCancel.Text = "ยกเลิกโดย VPS ตามคำร้องขอ ของลูกค้า<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
                btnCancel.Visible = False
                If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
        End Select
        Dim Load As String = ""
        Dim Disch As String = ""
        Dim LoadIRPC As String = ""
        Dim DischIRPC As String = ""
        For Each dr As DataRow In CType(Session("Product_popup"), DataTable).Rows
            Select Case dr.Item("Product_Event") & ""
                Case "L" : Load = "Y"
                Case "D" : Disch = "Y"
                Case "R" : LoadIRPC = "Y"
                Case "I" : LoadIRPC = "Y"
            End Select
            If (dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination") = "O") Then
                Session("Operation") = Load & "$" & Disch & "$" & LoadIRPC & "$" & DischIRPC & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination") & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy")
            Else
                Session("Operation") = Load & "$" & Disch & "$" & LoadIRPC & "$" & DischIRPC & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination") & "$" & ""
            End If
        Next
        Dim RemarkVPS As String = ""
        Dim FirstRemarkVPS As Boolean = True
        Dim TimeCreateRemark As String = ""
        Dim dsRemark As DataTable = clsGet.Get_Booking_LogRemarkVPS(booking_no, "VPS")
        If (dsRemark.Rows.Count > 0) Then
            rowRemarkVPS.Visible = True
            For Each drVPS As DataRow In dsRemark.Rows
                If (drVPS.Item("Remark_VPS") & "" <> "") Then
                    TimeCreateRemark = drVPS.Item("Booking_log")
                    If (FirstRemarkVPS) Then
                        RemarkVPS = TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_VPS")
                        FirstRemarkVPS = False
                    Else
                        RemarkVPS &= "<BR />" & TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_VPS")
                    End If
                End If
            Next
            If (RemarkVPS.Trim() = "") Then
                lbRemark_VPS.Text = String.Empty
                rowRemarkVPS.Visible = False
            Else
                lbRemark_VPS.Text = RemarkVPS
            End If
        Else
            lbRemark_VPS.Text = String.Empty
            rowRemarkVPS.Visible = False
        End If


        Dim RemarkMRI As String = ""
        Dim FirstRemarkMRI As Boolean = True
        TimeCreateRemark = ""
        dsRemark = clsGet.Get_Booking_LogRemarkVPS(booking_no, "MRI")
        If (dsRemark.Rows.Count > 0) Then
            rowRemarkMRI.Visible = True
            For Each drVPS As DataRow In dsRemark.Rows
                If (drVPS.Item("Remark_MRI") & "" <> "") Then
                    TimeCreateRemark = drVPS.Item("Booking_log")
                    If (FirstRemarkMRI) Then
                        RemarkMRI = TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_MRI")
                        FirstRemarkMRI = False
                    Else
                        RemarkMRI &= "<BR />" & TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_MRI")
                    End If
                End If
            Next
            If (RemarkMRI.Trim() = "") Then
                lbRemark_MRI.Text = String.Empty
                rowRemarkMRI.Visible = False
            Else
                lbRemark_MRI.Text = RemarkMRI
            End If
        Else
            lbRemark_MRI.Text = String.Empty
            rowRemarkMRI.Visible = False
        End If
        Try
            If (CType(Session("Product_popup"), DataTable).Rows.Count = 0) Then
                Session("Product_popup") = CreateDatasetProduct()
            End If
        Catch ex As Exception

        End Try
        If (dsBooking.Tables(0).Rows(0).Item("PORT") = "B") Then
            SetProductBulk(Session("Product_popup"))
        End If
        gridProduct.PageIndex = 0
        gridProduct.DataSource = Session("Product_popup")
        gridProduct.DataBind()
        gridTariff.PageIndex = 0
        gridTariff.DataSource = Session("MAT_USE")
        gridTariff.DataBind()
        gridfile.PageIndex = 0
        gridfile.DataSource = Session("Q88")
        gridfile.DataBind()
        ComputeTariff.Visible = False
        If (dsBooking.Tables(0).Rows.Count = 1) Then
            If (GetDataFromGridItem(booking_no, "Vehicle_no") = "999999999") Then 'gridItem.DataKeys(Index).Values("Vehicle_no")
                radioVehicle.SelectedValue = "1"
                PanelVEHICLE_OUT.Visible = True
                PanelVEHICLE_IN.Visible = False
                PanelVEHICLE_IN_DETAIL.Visible = False
                txtVesselOUT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
                txtLOA.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_LOA")
                txtDWT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_DWT").ToString().Trim()
                txtDraft.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_Draft")
                txtGRT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_GRT")
                If Not (ddlNation.Items.FindByValue(dsBooking.Tables(0).Rows(0).Item("Vehicle_CNTRY").ToString().Replace("TH", "T")) Is Nothing) Then
                    ddlNation.SelectedValue = dsBooking.Tables(0).Rows(0).Item("Vehicle_CNTRY").ToString().Replace("TH", "T")
                Else
                    ddlNation.SelectedValue = "O"
                End If
            Else
                radioVehicle.SelectedValue = "0"
                PanelVEHICLE_IN.Visible = True
                PanelVEHICLE_IN_DETAIL.Visible = True
                PanelVEHICLE_OUT.Visible = False
                txtVessel.Text = GetDataFromGridItem(booking_no, "Vehicle_no") & "-" & GetDataFromGridItem(booking_no, "Vehicle_Text") 'gridItem.DataKeys(Index).Values("Vehicle_no") & "-" & gridItem.DataKeys(Index).Values("Vehicle_Text")
                lbLOA.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_LOA")
                lbDWT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_DWT").ToString().Trim()
                lbDraft.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_Draft")
                lbGRT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_GRT")
                lbNation.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_CNTRY")
            End If
            txtDate.Text = dsBooking.Tables(0).Rows(0).Item("Date_From")
            txtDateTo.Text = dsBooking.Tables(0).Rows(0).Item("Date_To")
            txtDateBooking.Text = dsBooking.Tables(0).Rows(0).Item("Booking_Date")
            txtTimeBooking.Text = dsBooking.Tables(0).Rows(0).Item("Booking_Time")



            If ((dsBooking.Tables(0).Rows(0).Item("Lay_Time") & "" <> "0") And (dsBooking.Tables(0).Rows(0).Item("Lay_Time") & "" <> "")) Or ((dsBooking.Tables(0).Rows(0).Item("Demurrage") & "" = "0") And (dsBooking.Tables(0).Rows(0).Item("Demurrage") & "" = "")) Then
                radioDemurrage.ClearSelection()
                radioDemurrage.SelectedValue = "Y"
                rowLaytime.Visible = True

                txtLayTime.Text = dsBooking.Tables(0).Rows(0).Item("Lay_Time")
                txtDemurrage.Text = dsBooking.Tables(0).Rows(0).Item("Demurrage")
                If Not (ddlDemurrage.Items.FindByValue(dsBooking.Tables(0).Rows(0).Item("Demurrage_Money") & "") Is Nothing) Then
                    ddlDemurrage.SelectedValue = dsBooking.Tables(0).Rows(0).Item("Demurrage_Money") & ""
                End If
            Else
                txtLayTime.Text = "0"
                txtDemurrage.Text = "0"
                radioDemurrage.ClearSelection()
                radioDemurrage.SelectedValue = "N"
                rowLaytime.Visible = False
            End If

            txtWater.Text = dsBooking.Tables(0).Rows(0).Item("Water_Point")
            If (dsBooking.Tables(0).Rows(0).Item("BunkerFO_chk") & "" = "Y") Then
                chkFO.Checked = True
                txtFO.Text = dsBooking.Tables(0).Rows(0).Item("BunkerFO_Point") & ""
            Else
                txtFO.Text = "0"
            End If
            If (dsBooking.Tables(0).Rows(0).Item("BunkerDO_chk") & "" = "Y") Then
                chkDO.Checked = True
                txtDO.Text = dsBooking.Tables(0).Rows(0).Item("BunkerDO_Point") & ""
            Else
                txtDO.Text = "0"
            End If
            If Not (raioType.Items.FindByValue(dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination")) Is Nothing) Then
                raioType.SelectedValue = dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination")
                If (raioType.SelectedValue = "O") Then
                    rowTypeBuy.Visible = True
                    If Not (radioTypeBuy.Items.FindByValue(dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy")) Is Nothing) Then
                        radioTypeBuy.SelectedValue = dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy")
                    End If
                End If
            End If
            If Not (radioPort.Items.FindByValue(dsBooking.Tables(0).Rows(0).Item("PORT")) Is Nothing) Then
                radioPort.SelectedValue = dsBooking.Tables(0).Rows(0).Item("PORT")
            End If
            txtRemark.Text = dsBooking.Tables(0).Rows(0).Item("Remark")
        End If
        If ((ViewState("ST") & "" = "OA") Or (ViewState("ST") & "" = "FN")) Then
            btnCompute.Visible = False
            btnUpdate.Visible = False
        ElseIf ((ViewState("ST") & "" = "CC") Or (ViewState("ST") & "" = "CA") Or (ViewState("ST") & "" = "CV") Or (ViewState("ST") & "" = "CM") Or (ViewState("ST") & "" = "CR")) Then
            btnCompute.Visible = False
            btnCancelBooking.Visible = False
            rowCancel.Visible = True
            btnUpdate.Visible = False
        Else
            btnCompute.Visible = False
            btnUpdate.Visible = True
        End If
        If (dsBooking.Tables(0).Rows(0).Item("Marketing_approve") & "" = "") And (dsBooking.Tables(0).Rows(0).Item("VPS_approve") & "" = "") Then
            If PanelVEHICLE_IN.Visible Then
                btnSearch.Visible = True
                txtVessel.Enabled = True
            Else
                btnSearchOUT.Visible = True
                txtVesselOUT.Enabled = True
                txtLOA.Enabled = True
                txtGRT.Enabled = True
                txtDWT.Enabled = True
                txtDraft.Enabled = True
                ddlNation.Enabled = True
            End If

        Else
            If PanelVEHICLE_IN.Visible Then
                btnSearch.Visible = False
                txtVessel.Enabled = False
            Else
                btnSearchOUT.Visible = False
                txtVesselOUT.Enabled = False
                txtLOA.Enabled = False
                txtGRT.Enabled = False
                txtDWT.Enabled = False
                txtDraft.Enabled = False
                ddlNation.Enabled = False
            End If
        End If
    End Sub
    Private Sub btnReLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReLoad.Click
        gridItem.DataSource = ViewState("Booking")
        gridItem.DataBind()
        ShowPanelForRole()
        ViewState("Load") = "Not"
        Timer1_Tick(sender, e)
    End Sub
    Private Sub gridItem_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridItem.RowEditing
        'testLabel.Text = "xxxx"
    End Sub

    Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        Try
            If (radioPort.SelectedValue = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการเลือกท่าเรือ !!');", True)
                Exit Sub
            End If
            If (txtid.Text.Trim <> "") Then
                If ((clsGet.Get_Customer(txtid.Text.Trim().Split("-")(0))).Rows.Count < 1) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Sub Agent !!');", True)
                    Exit Sub
                End If
            End If
            If (txtAgent.Text.Trim <> "") Then
                If ((clsGet.Get_Customer(txtAgent.Text.Trim().Split("-")(0))).Rows.Count < 1) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Main Agent !!');", True)
                    Exit Sub
                End If
            End If
            If Not (txtVessel.Text.Trim() = "") Then
                Dim ds As DataTable = clsGet.Get_VEHICLE_DETAIL(txtVessel.Text.Split("-")(0))
                If (ds.Rows.Count > 0) Then
                    'พบเรือ
                    If (UpdateVessel(txtVessel.Text.Split("-")(0))) Then
                        'Update Vessel
                        ds = clsGet.Get_VEHICLE_DETAIL(txtVessel.Text.Split("-")(0))
                        If Not (PanelDetail.Visible) Then
                            rowDetailAll.Visible = True
                            PanelDetail.Visible = True
                            txtVessel.Enabled = False
                            txtAgent.Enabled = False
                            txtid.Enabled = False
                            radioVehicle.Enabled = False
                            btnSearch.Visible = False
                            radioPort.Enabled = False

                        End If
                        'Bind Data VEHICLE Detail
                        lbLOA.Text = (CDbl(ds.Rows(0).Item("VEH_LENGTH")) * 3.281).ToString("############0.00")
                        lbDWT.Text = ds.Rows(0).Item("VEH_MAXWGT_C").ToString().Trim()
                        lbDraft.Text = (CDbl(ds.Rows(0).Item("DRAFT")) * 3.281).ToString("############0.00")
                        lbNation.Text = ds.Rows(0).Item("REG_CNTRY")
                        If Not ((ds.Rows(0).Item("STCMNR") & "").ToString().Trim() = "") Then
                            Try
                                lbGRT.Text = ds.Rows(0).Item("STCMNR").ToString().Replace("GRT", "").Replace("=", "").Replace("MT", "")
                            Catch ex As Exception

                            End Try
                        End If
                        If (lbLOA.Text.Trim() = "") Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล LOA !!');", True)
                            Exit Sub
                        End If
                        If (lbDWT.Text.Trim() = "") Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล DWT !!');", True)
                            Exit Sub
                        End If
                        If (lbDraft.Text.Trim() = "") Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Draft !!');", True)
                            Exit Sub
                        End If
                        If (lbNation.Text.Trim() = "") Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล FLAG !!');", True)
                            Exit Sub
                        End If
                        If (lbGRT.Text.Trim() = "") Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล GRT !!');", True)
                            Exit Sub
                        End If
                        PanelVEHICLE_IN_DETAIL.Visible = True

                        If (Session("Role") = "00002") Then
                            btnCompute.Visible = True
                        End If
                    End If

                Else
                    'ไม่พบเรือ
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ข้อมูลเรือไม่ถูกต้อง!!');", True)
                End If
            Else
                'ยังไม่ระบุข้อมูลเรือ
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเรือ!!');", True)
            End If

        Catch ex As Exception
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่สามารถทำการเชื่อมต่อ SAP ได้!!');", True)
        End Try
    End Sub

    Private Sub btnLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLoad.Click
        gridTariff.PageIndex = 0
        gridTariff.DataSource = Session("MAT_USE")
        gridTariff.DataBind()
    End Sub

    Private Sub radioVehicle_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioVehicle.SelectedIndexChanged
        If (radioVehicle.SelectedValue = "0") Then
            'In
            txtVessel.Text = txtVesselOUT.Text
            PanelVEHICLE_IN.Visible = True
            PanelVEHICLE_OUT.Visible = False
            lbFT1.Text = "FT"
            lbFT2.Text = "FT"
        Else
            'OUT
            txtVesselOUT.Text = txtVessel.Text
            PanelVEHICLE_IN.Visible = False
            PanelVEHICLE_OUT.Visible = True
            lbFT1.Text = "FT"
            lbFT2.Text = "FT"
        End If
    End Sub

    Private Sub btnSearchOUT_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchOUT.Click
        If (txtid.Text.Trim <> "") Then
            If ((clsGet.Get_Customer(txtid.Text.Trim().Split("-")(0))).Rows.Count < 1) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Sub Agent !!');", True)
                Exit Sub
            End If
        End If
        If (txtAgent.Text.Trim <> "") Then
            If ((clsGet.Get_Customer(txtAgent.Text.Trim().Split("-")(0))).Rows.Count < 1) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Main Agent !!');", True)
                Exit Sub
            End If
        End If
        If (txtLOA.Text.Trim = "") Or (txtDWT.Text.Trim() = "") Or (txtDraft.Text.Trim() = "") Or (txtGRT.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุข้อมูลเรือให้ครบ !!');", True)
            Exit Sub
        End If
        If Not (txtVesselOUT.Text.Trim() = "") Then
            PanelDetail.Visible = True
            txtVesselOUT.Enabled = False
            radioVehicle.Enabled = False
            txtLOA.Enabled = False
            txtDWT.Enabled = False
            txtDraft.Enabled = False
            txtGRT.Enabled = False
            txtid.Enabled = False
            ddlNation.Enabled = False
            btnSearchOUT.Visible = False
            radioPort.Enabled = False
            rowDetailAll.Visible = True
            If (Session("Role") = "00002") Then
                btnCompute.Visible = True
            End If
            '  LoadDefault_MAT(ddlNation.SelectedValue)
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเรือ!!');", True)
        End If
    End Sub

    Private Sub btnCompute_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCompute.Click
        If (Session("Role") & "" = "00002") Then
            If Not (ComputeMAT()) Then
                Exit Sub
            End If
        End If
        Dim dsProduct As DataTable = Session("Product_popup")
        If (gridProduct.DataKeys(0).Values("Product_no") & "" <> "") Then
            If dsProduct Is Nothing Then
                Response.Redirect("../Form/Logon.aspx", True)
            End If
            If (dsProduct.Rows.Count = 0) Then
                Response.Redirect("../Form/Logon.aspx", True)
            End If
        End If

        Dim StandardTimePlus As String = "0"
        If chkFO.Checked Then
            StandardTimePlus = ((CInt(txtFO.Text) * 45) \ 60).ToString() & "." & ((CInt(txtFO.Text) * 45) Mod 60).ToString("00")
        End If
        If (chkDO.Checked) Then
            StandardTimePlus = (CDbl(StandardTimePlus) + CDbl(((CInt(txtDO.Text) * 45) \ 60).ToString() & "." & ((CInt(txtDO.Text) * 45) Mod 60).ToString("00"))).ToString("#########.00")
        End If
        If (txtWater.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Water กรณีไม่มีการใช้กรุณาระบุเป็น 0!!');", True)
            Exit Sub
        End If
        If (txtElectricity.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Electricity กรณีไม่มีการใช้กรุณาระบุเป็น 0!!');", True)
            Exit Sub
        End If
        If (txtDemurrage.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Demurrage กรณีไม่มีการใช้กรุณาระบุเป็น 0!!');", True)
            Exit Sub
        End If
        Dim dtQ88 As DataTable = Session("Q88")
        Dim chkQ88 As Boolean = True
        Dim q88count As Integer = dtQ88.Rows.Count
        For Each dr As DataRow In dtQ88.Rows
            Dim upType As String = dr.Item("Upload_Type").ToString()
            If (dr.Item("Upload_Type") = "Q88") Then
                chkQ88 = False
                Exit For
            End If
        Next
        If (chkQ88) Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการแนบเอกสาร Q88!!');", True)
            Exit Sub
        End If
        If (txtWater.Text.Trim() <> "0") Then
            Dim dst As DataSet = Session("MAT_USE")
            Dim cNew As Boolean = True
            For Each dr As DataRow In dst.Tables(0).Rows
                If (dr.Item("MATERIAL") = "WP") Then
                    dr.Item("Count") = txtWater.Text
                    dst.AcceptChanges()
                    cNew = False
                    Exit For
                End If
            Next
            If (cNew) Then
                Dim Plant As String = ""
                If (radioPort.SelectedValue = "L") Then
                    Plant = "1103"
                Else
                    Plant = "1104"
                End If
                Dim dtMat As DataSet = clsGet.Get_MeterailDefault("WP", False, "''", "", "", "", "", "", "", "", Plant)
                If (dtMat.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dst.Tables(0).NewRow()
                    dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL") & ""
                    dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line") & ""
                    dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = txtWater.Text
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_ComputeM") = "Y"
                    dst.Tables(0).Rows.Add(dr)
                    dst.AcceptChanges()
                    Session("MAT_USE") = dst
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ท่าเรือนี้ไม่ได้ทำการจำหน่ายน้ำ!!');", True)
                    Exit Sub
                End If
            End If


        End If
        If (txtElectricity.Text.Trim() <> "0") Then
            Dim dst As DataSet = Session("MAT_USE")
            Dim cNew As Boolean = True
            For Each dr As DataRow In dst.Tables(0).Rows
                If (dr.Item("MATERIAL") = "ELEC.POWER") Then
                    dr.Item("Count") = txtWater.Text
                    dst.AcceptChanges()
                    cNew = False
                    Exit For
                End If
            Next
            If (cNew) Then
                Dim Plant As String = ""
                If (radioPort.SelectedValue = "L") Then
                    Plant = "1103"
                Else
                    Plant = "1104"
                End If
                Dim dtMat As DataSet = clsGet.Get_MeterailDefault("ELEC.POWER", False, "''", "", "", "", "", "", "", "", Plant)
                If (dtMat.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dst.Tables(0).NewRow()
                    dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL") & ""
                    dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line") & ""
                    dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = txtElectricity.Text
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_ComputeM") = "Y"
                    dst.Tables(0).Rows.Add(dr)
                    dst.AcceptChanges()
                    Session("MAT_USE") = dst
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ท่าเรือนี้ไม่ได้ทำการจำหน่ายไฟฟ้า!');", True)
                    Exit Sub
                End If
            End If
        End If
        'If (chkShifting.Checked) Then
        '    Dim Plant As String = ""
        '    If (radioPort.SelectedValue = "L") Then
        '        Plant = "1103"
        '    Else
        '        Plant = "1104"
        '    End If
        '    Dim MatShifting As DataTable = clsGet.Get_Meterial_Shifting(Plant)
        '    Dim dst As DataSet = Session("MAT_USE")
        '    Dim cNew As Boolean = True
        '    For Each dsf As DataRow In MatShifting.Rows
        '        For Each dr As DataRow In dst.Tables(0).Rows
        '            If (dr.Item("MATERIAL") = dsf.Item("MATERIAL")) Then
        '                cNew = False
        '                Exit For
        '            End If
        '        Next
        '        If (cNew) Then
        '            Dim dr As DataRow = dst.Tables(0).NewRow()
        '            dr.Item("MATERIAL") = dst.Tables(0).Rows(0).Item("MATERIAL") & ""
        '            dr.Item("Text_line") = dst.Tables(0).Rows(0).Item("Text_line") & ""
        '            dr.Item("Unit") = dst.Tables(0).Rows(0).Item("Unit") & ""
        '            dr.Item("Count") = "1"
        '            dr.Item("MAT_Default") = "N"
        '            dr.Item("KBETR") = dst.Tables(0).Rows(0).Item("KBETR") & ""
        '            dr.Item("KONWA") = dst.Tables(0).Rows(0).Item("KONWA") & ""
        '            dr.Item("MAT_Relation") = dst.Tables(0).Rows(0).Item("Mat_Relation") & ""
        '            dr.Item("MAT_ComputeM") = "Y"
        '            dst.Tables(0).Rows.Add(dr)
        '            dst.AcceptChanges()
        '            Session("MAT_USE") = dst
        '        End If

        '    Next

        'End If


        Session("StandardTimePlus") = CInt(StandardTimePlus)
        ' Dim dsProduct As DataTable = Session("Product_popup")
        Dim ProductName As String = ""
        Dim ProductAmount As Double = 0.0
        Dim ProductAmountByLine As String = ""
        Dim ProductAmountByProduct As String = ""
        Dim ProductType As String = ""
        Dim ProductBuyer As String = ""
        Dim ProductSeller As String = ""
        For Each dr As DataRow In dsProduct.Rows
            If (dr.Item("Product_name") & "" <> "") Then
                ProductName &= "," & dr.Item("Product_name")
                ProductAmountByLine &= "," & dr.Item("Product_Amount")
                ProductAmount = ProductAmount + (CDbl(dr.Item("Product_Amount")))
                ProductType &= "," & dr.Item("Product_Unit")
                ProductBuyer &= "," & dr.Item("Product_BUYER_name")
                ProductSeller &= "," & dr.Item("Product_SELLER_name")
                ProductAmountByProduct &= dr.Item("Product_name") & "฿" & dr.Item("Product_Amount") & "฿"
            End If
        Next
        If (ProductName.Length > 0) Then
            ProductName = ProductName.Substring(1, ProductName.Length - 1)
            ProductAmountByLine = ProductAmountByLine.Substring(1, ProductAmountByLine.Length - 1)
            ProductType = ProductType.Substring(1, ProductType.Length - 1)
            ProductBuyer = ProductBuyer.Substring(1, ProductBuyer.Length - 1)
            ProductSeller = ProductSeller.Substring(1, ProductSeller.Length - 1)
        End If

        ViewState("Product_NameAmount") = ProductName & "$" & ProductAmount & "$" & ProductType & "$" & ProductBuyer & "$" & ProductSeller
        If (radioVehicle.SelectedValue = "0") Then
            Dim ds As DataTable = clsGet.Get_VEHICLE_DETAIL(txtVessel.Text.Split("-")(0))
            If (ds.Rows.Count > 0) Then
                Dim NameAgent As String = ""
                Dim CodeAgent As String = ""
                If (txtid.Text.Trim() <> "") Then
                    Dim AgentLoops() As String = txtid.Text.Split("-")
                    For i As Integer = 0 To AgentLoops.Length - 1
                        If (i <> 0) Then
                            NameAgent &= "-" & AgentLoops(i).ToString()
                        End If
                    Next
                    CodeAgent = txtid.Text.Split("-")(0)
                    NameAgent = txtid.Text.Split("-")(0) & "-" & NameAgent.Substring(1, NameAgent.Length - 1)
                End If
                Dim tVessel As String = ""
                Dim AgentLoop() As String = txtVessel.Text.Split("-")
                For i As Integer = 0 To AgentLoop.Length - 1
                    If (i <> 0) Then
                        tVessel &= "-" & AgentLoop(i).ToString()
                    End If
                Next
                Dim Nation As String = ""
                If lbNation.Text = "TH" Then
                    Nation = "T"
                Else
                    Nation = "O"
                End If
                tVessel = tVessel.Substring(1, tVessel.Length - 1)
                Session("Value") = NameAgent & "$" & tVessel & "$" & ProductName & "$" & lbDWT.Text & "$" & lbLOA.Text & "$" & ProductAmount & "$" & lbDraft.Text & "$Draft$" & raioType.SelectedValue & "$" & radioTypeBuy.SelectedValue & "$" & Nation & "$" & lbGRT.Text & "$" & radioPort.SelectedValue & "$" & ProductAmountByProduct & "$" & CodeAgent
                '  Session("Value") = lbLOA.Text & "$" & lbDWT.Text & "$" & lbDraft.Text & "$" & lbGRT.Text & "$" & tVessel & "$" & NameAgent & "$Draft" & "$" & ProductName & "$" & ProductAmount & "$" & ProductAmountByProduct & "$" & lbNation.Text & "$" & raioType.SelectedValue & "$" & ViewState("Status")
            Else
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ข้อมูลเรือไม่ถูกต้อง!!');", True)
                Exit Sub
            End If
        Else
            Dim nation As String = "XX"
            nation = ddlNation.SelectedValue
            Dim NameAgent As String = ""
            Dim CodeAgent As String = ""
            If (txtid.Text.Trim() <> "") Then
                Dim AgentLoops() As String = txtid.Text.Split("-")
                For i As Integer = 0 To AgentLoops.Length - 1
                    If (i <> 0) Then
                        NameAgent &= "-" & AgentLoops(i).ToString()
                    End If
                Next
                CodeAgent = txtid.Text.Split("-")(0)
                NameAgent = NameAgent.Substring(1, NameAgent.Length - 1)
            End If
            Session("Value") = NameAgent & "$" & txtVesselOUT.Text & "$" & ProductName & "$" & txtDWT.Text & "$" & txtLOA.Text & "$" & ProductAmount & "$" & txtDraft.Text & "$Draft$" & raioType.SelectedValue & "$" & radioTypeBuy.SelectedValue & "$" & nation & "$" & txtGRT.Text & "$" & radioPort.SelectedValue & "$" & ProductAmountByProduct & "$" & CodeAgent
            ' Session("Value") = txtLOA.Text & "$" & txtDWT.Text & "$" & txtDraft.Text & "$" & txtGRT.Text & "$" & txtVesselOUT.Text & "$" & NameAgent & "$Draft" & "$" & ProductName & "$" & ProductAmount & "$" & ProductAmountByProduct & "$" & nation & "$" & raioType.SelectedValue & "$" & ViewState("Status")
        End If
        If (radioPort.SelectedValue = "B") Then
            If Not (ViewState("OwnerColumn") & "" = "") Then
                Dim dsBulk As DataSet = Session("MAT_USE")
                Dim dsNewBulk As New DataSet
                Dim Owner() As String = ViewState("OwnerColumn").ToString.Split("$")
                Dim Count As Integer = 0
                For i As Integer = 0 To Owner.Length - 1
                    Dim _Owner As String = Owner(i).Split("฿")(0)
                    If (Owner(i).Split("฿")(1) <> "") Then
                        'ทำการแยก DataTable ของลูกค้าแต่ละคนออกจากกันเลย
                        Dim dtN As DataTable = dsBulk.Tables(0).Clone
                        If (dtN.Columns.Count < 10) Then
                            dtN.Columns.Add("Owner", GetType(String))
                            dtN.AcceptChanges()
                        End If
                        For j As Integer = 0 To gridTariff.Rows.Count - 1
                            Dim chk As CheckBox = CType(gridTariff.Rows(j).FindControl("chkOwner" & Count + 1), CheckBox)
                            If (chk.Checked) Then
                                Dim dr As DataRow = dtN.NewRow
                                dr.Item("MATERIAL") = gridTariff.DataKeys(j).Values("MATERIAL") & ""
                                dr.Item("Text_line") = gridTariff.DataKeys(j).Values("Text_line") & ""
                                dr.Item("Unit") = gridTariff.DataKeys(j).Values("Unit") & ""
                                dr.Item("Count") = gridTariff.DataKeys(j).Values("Count") & ""
                                dr.Item("MAT_Default") = gridTariff.DataKeys(j).Values("MAT_Default") & ""
                                dr.Item("KBETR") = gridTariff.DataKeys(j).Values("KBETR") & ""
                                dr.Item("KONWA") = gridTariff.DataKeys(j).Values("KONWA") & ""
                                dr.Item("MAT_Relation") = gridTariff.DataKeys(j).Values("Mat_Relation") & ""
                                dr.Item("MAT_ComputeM") = gridTariff.DataKeys(j).Values("MAT_ComputeM") & ""
                                dr.Item("Owner") = _Owner
                                dtN.Rows.Add(dr)
                                dtN.AcceptChanges()
                            End If
                        Next
                        Count += 1
                        dtN.TableName = "Bulk" & Count
                        dsNewBulk.Tables.Add(dtN.Copy)
                    End If
                Next
                Session("MAT_USE") = dsNewBulk
            End If

        End If
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_framePopup2').src = '../FormPopup/estimate.aspx';", True)
        Session("EditBooking_Show") = ViewState("EditBooking")
        ModalPopupExtender2.Show()

    End Sub

    Private Function CheckParameter() As Boolean
        If (txtDate.Text = "") Then
            Return False
        End If
        If (txtDateTo.Text = "") Then
            Return False
        End If
        'Check Product
        'Dim ds As DataTable = Session("Product_popup")
        'If (ds.Rows(0).Item("Product_name") & "" = "") Then
        '    Return False
        'End If
        If (radioPort.SelectedIndex = -1) Then
            Return False
        End If
        If (raioType.SelectedValue = "") Then
            Return False
        End If
        If (raioType.SelectedValue = "O") Then
            If (radioTypeBuy.SelectedValue = "") Then
                Return False
            End If
        End If
        Return True
    End Function

    Private Sub btnSaveBooking_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveBooking.Click
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Application.Lock()
        conn.Open()
        Dim Booking As String = ""
        If (ViewState("EditBooking") & "" = "") Then
            Dim Pre_Booking As String = clsDB.GeneratorID(conn, "Pre_Booking")
            Booking = clsDB.GeneratorID(conn, "Booking")
            If (CInt(Pre_Booking) > CInt(Booking)) Then
                Booking = Pre_Booking
            End If
        Else
            Booking = ViewState("EditBooking")
        End If

        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
        Dim Vehicle As String = ""
        Dim Vehicle_Name As String = ""
        Dim LOA As String = ""
        Dim DWT As String = ""
        Dim Draft As String = ""
        Dim GRT As String = ""
        Dim OwnerRequest As String = ""
        Dim CNTRY As String = ""
        Dim Vehicle_TypeBuy As String = ""
        Dim BunkerFO_chk As String = ""
        Dim BunkerDO_chk As String = ""
        Dim BunkerFO_Point As String = ""
        Dim BunkerDO_Point As String = ""

        Dim Product_Name As String = ViewState("Product_NameAmount").ToString().Split("$")(0)
        If (chkFO.Checked) Then
            BunkerFO_chk = "Y"
            BunkerFO_Point = txtFO.Text.Trim()
            If (Product_Name.Trim <> "") Then
                Product_Name &= ",BunkerFO " & BunkerFO_Point & " คัน"
            Else
                Product_Name &= "BunkerFO " & BunkerFO_Point & " คัน"
            End If
        Else
            BunkerFO_chk = "N"
            BunkerFO_Point = "0"
        End If

        'If (lbFT1.Text = "FT") Then
        '    If (txtLOA.Text.Trim() <> "") Then
        '        Try
        '            txtLOA.Text = (CDbl(txtLOA.Text) * 3.281).ToString("############0.00")
        '        Catch ex As Exception

        '        End Try
        '    End If
        '    If (txtDraft.Text.Trim() <> "") Then
        '        Try
        '            txtDraft.Text = (CDbl(txtDraft.Text) * 3.281).ToString("############0.00")
        '        Catch ex As Exception

        '        End Try
        '    End If
        'End If

        If (chkDO.Checked) Then
            BunkerDO_chk = "Y"
            BunkerDO_Point = txtDO.Text.Trim()
            If (Product_Name.Trim <> "") Then
                Product_Name &= ",BunkerDO " & BunkerDO_Point & " คัน"
            Else
                Product_Name &= "BunkerDO " & BunkerDO_Point & " คัน"
            End If
        Else
            BunkerDO_chk = "N"
            BunkerDO_Point = "0"
        End If

        Dim File_Upload As String = ""
        Dim dt As DataTable = Session("Q88")
        For Each dr As DataRow In dt.Rows
            'File_Upload = File_Upload.Replace("," & dr.Item("File_Type"), "")
            'File_Upload &= "," & dr.Item("File_Type")
            File_Upload &= "," & dr.Item("File_name")
        Next
        If (File_Upload.Length > 0) Then
            File_Upload = File_Upload.Substring(1, File_Upload.Length - 1)
        End If

        Dim MAgent_no As String = ""
        Dim MAgent_name As String = ""
        Dim SAgent_name As String = ""
        Dim SAgent_no As String = ""
        If (txtid.Text.Trim = "") Then
            MAgent_no = ""
            MAgent_name = ""
        Else
            MAgent_no = txtid.Text.Split("-")(0)
            ' MAgent_name = txtid.Text.Split("-")(1)
            Dim AgentLoops() As String = txtid.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    MAgent_name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            MAgent_name = MAgent_name.Substring(1, MAgent_name.Length - 1)
        End If
        If (txtAgent.Text.Trim = "") Then
            SAgent_no = ""
            SAgent_name = ""
        Else
            SAgent_no = txtAgent.Text.Split("-")(0)
            'SAgent_name = txtAgent.Text.Split("-")(1)
            Dim AgentLoops() As String = txtAgent.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    SAgent_name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            SAgent_name = SAgent_name.Substring(1, SAgent_name.Length - 1)
        End If
        If (raioType.SelectedValue = "O") Then
            Vehicle_TypeBuy = radioTypeBuy.SelectedValue
        End If
        If (Session("Role") & "" = "00002") Then
            OwnerRequest = ""
        Else
            OwnerRequest = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name")
        End If
        Dim standardTime As String = ""
        If (Session("Lay_Time") & "" = "") Then
            standardTime = "0"
        Else
            standardTime = Session("Lay_Time") & ""
        End If
        If (radioVehicle.SelectedValue = "0") Then
            Vehicle = txtVessel.Text.Split("-")(0)
            '  Vehicle_Name = txtVessel.Text.Split("-")(1)
            Dim AgentLoops() As String = txtVessel.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    Vehicle_Name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            Vehicle_Name = Vehicle_Name.Substring(1, Vehicle_Name.Length - 1)
            LOA = lbLOA.Text.Trim()
            DWT = lbDWT.Text.Trim()
            Draft = lbDraft.Text.Trim()
            GRT = lbGRT.Text.Trim()
            CNTRY = lbNation.Text.Trim()
        Else
            Vehicle = "999999999"
            Vehicle_Name = txtVesselOUT.Text.Trim()
            LOA = txtLOA.Text.Trim()
            DWT = txtDWT.Text.Trim()
            Draft = txtDraft.Text.Trim()
            GRT = txtGRT.Text.Trim()
            CNTRY = ddlNation.SelectedValue.Replace("T", "TH")
        End If
        Dim shifting As String = ""
        tran = clsDB.BeginTran(conn)
        Try
            If (clsFc.InsertBooking(ViewState("EditBooking"), Booking, hdfUsername.Value, txtName.Text, Vehicle, Vehicle_Name, LOA, DWT, Draft, GRT, txtDate.Text, txtDateTo.Text, radioPort.SelectedValue, raioType.SelectedValue, Vehicle_TypeBuy, txtRemark.Text, "NB", "", "", "", "", "", Product_Name, ViewState("Product_NameAmount").ToString().Split("$")(1), MAgent_no, MAgent_name, SAgent_no, SAgent_name, txtDateBooking.Text, txtTimeBooking.Text, ViewState("Product_NameAmount").ToString().Split("$")(3), ViewState("Product_NameAmount").ToString().Split("$")(4), ViewState("Product_NameAmount").ToString().Split("$")(2), File_Upload, CNTRY, txtLayTime.Text.Trim(), "N", "N", "N", BunkerFO_chk, BunkerDO_chk, BunkerFO_Point, BunkerDO_Point, txtBunkerDetail.Text, txtWater.Text.Trim(), "", standardTime, "", txtDemurrage.Text, ddlDemurrage.SelectedValue, txtElectricity.Text, shifting, conn, tran) > 0) Then
                If (clsFc.InsertBooking_Log(Booking_Log, Booking, hdfUsername.Value, txtName.Text, Vehicle, Vehicle_Name, LOA, DWT, Draft, GRT, txtDate.Text, txtDateTo.Text, radioPort.SelectedValue, raioType.SelectedValue, Vehicle_TypeBuy, txtRemark.Text, "NB", "", "", "", "", "", Product_Name, ViewState("Product_NameAmount").ToString().Split("$")(1), MAgent_no, MAgent_name, SAgent_no, SAgent_name, txtDateBooking.Text, txtTimeBooking.Text, ViewState("Product_NameAmount").ToString().Split("$")(3), ViewState("Product_NameAmount").ToString().Split("$")(4), ViewState("Product_NameAmount").ToString().Split("$")(2), File_Upload, CNTRY, txtLayTime.Text, "N", "N", "N", BunkerFO_chk, BunkerDO_chk, BunkerFO_Point, BunkerDO_Point, txtBunkerDetail.Text, txtWater.Text.Trim(), "", "", "", "", "", "", "", "", standardTime, "", "N", txtDemurrage.Text, ddlDemurrage.SelectedValue, txtElectricity.Text, shifting, conn, tran) > 0) Then
                    Dim dsMat As DataSet = Session("MAT_USE")
                    clsFc.DeleteBookingTariff(Booking, "", conn, tran)
                    If (radioPort.SelectedValue = "L") Then
                        For Each dr As DataRow In dsMat.Tables(0).Rows
                            If (clsFc.InsertBookingTariff(dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", Session("SumTotal") & "", conn, tran) > 0) Then
                                If (clsFc.InsertBookingTariff_Log(Booking_Log, dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", conn, tran) < 1) Then
                                    condition = False
                                    Exit For
                                End If
                            Else
                                condition = False
                                Exit For
                            End If
                        Next
                    Else
                        For Each dtMat As DataTable In dsMat.Tables
                            Try
                                For Each dr As DataRow In dtMat.Rows
                                    If (clsFc.InsertBookingTariff(dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", dr.Item("Owner"), Session("SumTotal") & "", conn, tran) > 0) Then
                                        If (clsFc.InsertBookingTariff_Log(Booking_Log, dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", dr.Item("Owner"), conn, tran) < 1) Then
                                            condition = False
                                            Exit For
                                        End If
                                    Else
                                        condition = False
                                        Exit For
                                    End If
                                Next
                            Catch ex As Exception
                                For Each dr As DataRow In dsMat.Tables(0).Rows
                                    If (clsFc.InsertBookingTariff(dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", Session("SumTotal") & "", conn, tran) > 0) Then
                                        If (clsFc.InsertBookingTariff_Log(Booking_Log, dr.Item("MATERIAL"), Booking, dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", conn, tran) < 1) Then
                                            condition = False
                                            Exit For
                                        End If
                                    Else
                                        condition = False
                                        Exit For
                                    End If
                                Next
                            End Try

                        Next
                    End If

                    Dim dsProduct As DataTable = Session("Product_popup")
                    clsFc.DeleteBookingProduct(Booking, conn, tran)
                    For Each dr As DataRow In dsProduct.Rows
                        If (dr.Item("Product_no") & "" <> "") Then
                            Dim Destination As String = ""
                            If (dr.Item("Product_Event") = "L") Or (dr.Item("Product_Event") = "R") Then
                                Destination = dr.Item("LoadDestination")
                            Else
                                Destination = dr.Item("DischDestination")
                            End If
                            If (clsFc.InsertBooking_Product("", Booking, dr.Item("Product_no"), dr.Item("Product_name"), dr.Item("Product_Amount"), dr.Item("Product_Event"), dr.Item("Group_no"), dr.Item("Group_name"), dr.Item("Product_Buyer_no"), dr.Item("Product_Buyer_name"), dr.Item("Product_Seller_no"), dr.Item("Product_Seller_name"), dr.Item("LoadDestination"), dr.Item("DischDestination"), dr.Item("DestinationShow"), dr.Item("Product_Description"), dr.Item("Product_Unit"), dr.Item("Owner_Product_no"), dr.Item("Owner_Product_name"), conn, tran) < 1) Then
                                'If (clsFc.InsertBooking_Product_Log(Booking_Log, Booking, dr.Item("Product_no"), dr.Item("Product_name"), dr.Item("Product_Amount"), dr.Item("Product_Event"), dr.Item("Group_no"), dr.Item("Group_name"), dr.Item("Product_Buyer_no"), dr.Item("Product_Buyer_name"), dr.Item("Product_Seller_no"), dr.Item("Product_Seller_name"), dr.Item("LoadDestination"), dr.Item("DischDestination"), dr.Item("DestinationShow"), dr.Item("Product_Description"), dr.Item("Product_Unit"), dr.Item("Owner_Product_no"), dr.Item("Owner_Product_name"), conn, tran) < 1) Then
                                '    condition = False
                                '    Exit For
                                'End If
                                ' Else
                                condition = False
                                Exit For
                            End If
                        End If

                    Next

                    clsFc.DeleteBooking_Upload(Booking, conn, tran)
                    For Each dr As DataRow In dt.Rows
                        If (clsFc.InsertBooking_Upload(Booking, dr.Item("File_nameGuid"), dr.Item("File_name"), dr.Item("File_type"), dr.Item("File_ContentType"), dr.Item("Upload_Type"), dr.Item("Description"), conn, tran) < 1) Then
                            condition = False
                            Exit For
                        End If
                    Next

                Else
                    condition = False
                End If
            Else
                condition = False
            End If
            If (condition) Then
                clsDB.CommitTran(tran)
                If (SendMail(GenBody("ลูกค้า " & txtName.Text & " ได้ทำการจองการใช้งานท่าเรือผ่านระบบ iPORT", Booking, MAgent_no & "-" & MAgent_name, Vehicle & "-" & Vehicle_Name, txtDate.Text & "-" & txtDateTo.Text))) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ  !!');", True)
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ  !!');", True)
                End If
                ViewState("EditBooking") = ""


                Session("Product_popup") = CreateDatasetProduct()
                Session("Lay_Time") = "0"

                Session("MAT_USE") = ""
                Session("Value") = Nothing
                Session("Q88") = CreateFileDataTable()
                Session("StandardTimePlus") = 0
                ViewState("Status") = ""
                Session("Operation") = Nothing
                PanelBookingItem.Visible = True
                PanelBooking.Visible = False
                ClearData()
                ShowPanelForRole()
                ViewState("Load") = "Not"
                Timer1_Tick(sender, e)
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก !!');", True)
            End If
        Catch ex As Exception
            clsDB.RollBackTran(tran)
            'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & ex.Message & "');", True)
            txtRemark.Text = ex.Message
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก  !!');", True)
        End Try
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub gridTariff_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridTariff.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        'If (gridItem.PageIndex <> 0) Then
        '    Index = Index Mod (gridItem.PageIndex * 10)
        'End If
        If e.CommandName = "cmddelete" Then
            Dim ds As DataSet = Session("MAT_USE")
            ds.Tables(0).Rows(Index).Delete()
            ds.Tables(0).AcceptChanges()
            Session("MAT_USE") = ds
            gridTariff.PageIndex = 0
            gridTariff.DataSource = Session("MAT_USE")
            gridTariff.DataBind()
        End If
    End Sub

    Private Sub gridTariff_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridTariff.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim ImgDelete As ImageButton = CType(e.Row.FindControl("imgdelete"), ImageButton)
            If (gridTariff.DataKeys(e.Row.RowIndex).Values("MAT_Default") & "" = "Y") Then
                ImgDelete.Visible = False
            End If
            If (gridTariff.DataKeys(e.Row.RowIndex).Values("MAT_Relation") & "" = "Y") Then
                e.Row.Cells(2).Text = "-"
            End If
            If (ViewState("EditBooking") & "" <> "") Then
                ImgDelete.Visible = False
            End If
        End If
    End Sub

    Public Sub Paginate(ByVal sender As Object, ByVal e As CommandEventArgs)
        Dim CurrentIndex As Integer = gridItem.PageIndex
        Select Case e.CommandArgument.ToString().ToLower()
            Case "first"
                gridItem.PageIndex = 0
            Case "prev"
                If (gridItem.PageIndex <> 0) Then
                    gridItem.PageIndex = CurrentIndex - 1
                End If
            Case "next"
                If (gridItem.PageIndex <> gridItem.PageCount) Then
                    gridItem.PageIndex = CurrentIndex + 1
                End If
            Case "last"
                gridItem.PageIndex = gridItem.PageCount
        End Select
        gridItem.DataSource = ViewState("Booking")
        gridItem.DataBind()
        ViewState("Load") = "Not"
        Timer1_Tick(sender, e)
    End Sub

    Protected Sub ddlPage_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim Page As GridViewRow = gridItem.BottomPagerRow
        Dim ddlPage As DropDownList = CType(Page.Cells(0).FindControl("ddlPage"), DropDownList)
        gridItem.PageIndex = ddlPage.SelectedIndex
        gridItem.DataSource = ViewState("Booking")
        gridItem.DataBind()
        ViewState("Load") = "Not"
        Timer1_Tick(sender, e)
    End Sub

    Private Sub gridItem_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridItem.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim rowIndex As Integer = e.Row.RowIndex
            Dim lbtnBookingNo As LinkButton = New LinkButton()
            lbtnBookingNo = CType(e.Row.FindControl("LinkBooking"), LinkButton)
            lbtnBookingNo.CommandArgument = rowIndex & ";" & gridItem.DataKeys(rowIndex)("Booking_no")

            'Detail Button
            'Dim detailBtn As Button = New Button()
            'detailBtn = CType(e.Row.FindControl("btnDetail"), Button)
            'detailBtn.CommandArgument = rowIndex & ";" & gridItem.DataKeys(rowIndex)("Booking_no")
            Dim dtLbtn As LinkButton = New LinkButton()
            dtLbtn = CType(e.Row.FindControl("DetailLbtn"), LinkButton)
            dtLbtn.CommandArgument = rowIndex & ";" & gridItem.DataKeys(rowIndex)("Booking_no")
            'dtLbtn.Text = "<input type='button' value='Detail' class='ButtonStyle detailbtn' style='width:70px'/>"

            Dim imgVPS As Image = CType(e.Row.FindControl("imgVPS"), Image)
            Dim imgMRI As Image = CType(e.Row.FindControl("imgMRI"), Image)
            Dim imgVPSComment As Image = CType(e.Row.FindControl("imgVPSComment"), Image)
            Dim imgMRIComment As Image = CType(e.Row.FindControl("imgMRIComment"), Image)
            Dim imgMKT As Image = CType(e.Row.FindControl("imgMKT"), Image)
            Dim imgProduct As Image = CType(e.Row.FindControl("imgProduct"), Image)
            Dim imgCustom As Image = CType(e.Row.FindControl("imgCustom"), Image)
            Dim imgFinance As Image = CType(e.Row.FindControl("imgFinance"), Image)
            clsFc.GetImageStatus(imgVPS, imgMRI, imgMKT, gridItem.DataKeys(e.Row.RowIndex).Values("VPS_approve"), gridItem.DataKeys(e.Row.RowIndex).Values("MRI_approve"), gridItem.DataKeys(e.Row.RowIndex).Values("Marketing_approve"), gridItem.DataKeys(e.Row.RowIndex).Values("Status"))
            clsFc.GetImageStatusMKT(imgProduct, imgCustom, imgFinance, gridItem.DataKeys(e.Row.RowIndex).Values("MKT_Product"), gridItem.DataKeys(e.Row.RowIndex).Values("MKT_Custom"), gridItem.DataKeys(e.Row.RowIndex).Values("MKT_Finance"))


            If (gridItem.DataKeys(e.Row.RowIndex).Values("Payin") & "" = "0") Then
                Dim dt As DataTable = clsGet.Get_Booking_Gl_Account(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"), gridItem.DataKeys(e.Row.RowIndex).Values("MAgent_no"))
                If (dt.Rows.Count > 0) Then
                    imgMKT.ImageUrl = "~/Image/green.png"
                Else
                    imgMKT.ImageUrl = "~/Image/red.png"
                End If
            ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Marketing_approve") & "" = "") Then
                imgMKT.ImageUrl = "~/Image/red.png"
            Else
                imgMKT.ImageUrl = "~/Image/green.png"
            End If

            If (gridItem.DataKeys(e.Row.RowIndex).Values("Remark_VPS") & "" <> "") Then
                imgVPSComment.Visible = True
            Else
                imgVPSComment.Visible = False
            End If
            If (gridItem.DataKeys(e.Row.RowIndex).Values("Remark_MRI") & "" <> "") Then
                imgMRIComment.Visible = True
            Else
                imgMRIComment.Visible = False
            End If

            Dim imgConfrim As Image = CType(e.Row.FindControl("imgConfrim"), Image)
            If (gridItem.DataKeys(e.Row.RowIndex).Values("Confirm_Time") & "" = "Y") Then
                imgConfrim.ImageUrl = "~/Image/4558.png"
            Else
                imgConfrim.ImageUrl = "~/Image/4557.gif"
            End If

            Dim Status As String = ""
            Dim Tooltip As String = ""
            clsGet.GetStatus_Working(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"), gridItem.DataKeys(e.Row.RowIndex).Values("PORT"), Status, Tooltip)
            e.Row.Cells(2).Text = Status
            e.Row.Cells(2).ToolTip = Tooltip

            If (gridItem.DataKeys(e.Row.RowIndex).Values("Date_From") & "" <> "") Then
                If (gridItem.DataKeys(e.Row.RowIndex).Values("Date_From") & "" = gridItem.DataKeys(e.Row.RowIndex).Values("Date_To") & "") Then
                    e.Row.Cells(3).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Date_To")
                Else
                    e.Row.Cells(3).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Date_From").ToString.Substring(0, 2) & "-" & gridItem.DataKeys(e.Row.RowIndex).Values("Date_To")
                End If

                e.Row.Cells(4).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Booking_Date") & " : " & gridItem.DataKeys(e.Row.RowIndex).Values("Booking_Time")
                e.Row.Cells(5).Text = e.Row.Cells(5).Text & " hours"
                If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "O") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_TypeBuy") & "" = "F") Then
                        e.Row.Cells(17).Text = "FOB" 'รูปแบบการซื้อขาย
                    ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_TypeBuy") & "" = "C") Then
                        e.Row.Cells(17).Text = "CFR"
                    ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_TypeBuy") & "" = "I") Then
                        e.Row.Cells(17).Text = "CIF"
                    Else
                        e.Row.Cells(17).Text = "อื่นๆ" 'รูปแบบการซื้อขาย
                    End If
                Else
                    e.Row.Cells(17).Text = "" 'รูปแบบการซื้อขาย
                    e.Row.Cells(16).Text = ""
                End If
                If (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage_Money") & "" = "B") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & "" = "") Then
                        e.Row.Cells(16).Text = "- BAHT"
                    Else
                        e.Row.Cells(16).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & " BAHT "
                    End If
                ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage_Money") & "" = "U") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & "" = "") Then
                        e.Row.Cells(16).Text = "- USD"
                    Else
                        e.Row.Cells(16).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & " USD "
                    End If
                End If
            End If

            Dim Product_Name As String = ""
            Dim Product_Amount As String = ""
            Dim Owner_name As String = ""
            Dim dtLog As DataTable
            dtLog = clsGet.Get_Booking_Product(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"))
            For Each dr As DataRow In dtLog.Rows
                If (dr.Item("Product_name") & "" <> "") Then
                    If (Product_Name <> "") Then
                        Product_Name &= "<br />" & dr.Item("Product_name") & ""
                        Product_Amount &= "<br />" & dr.Item("Product_Amount") & ""
                        Owner_name &= "<br />" & dr.Item("Owner_Product_Name") & ""
                    Else
                        Product_Name = dr.Item("Product_name") & ""
                        Product_Amount = dr.Item("Product_Amount") & ""
                        Owner_name = dr.Item("Owner_Product_Name") & ""
                    End If
                End If
            Next
            If (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & "" <> "") And (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & "" <> "0") Then
                'BunkerFO 1 คัน,BunkerDO 1 คัน
                If Product_Name = "" Then
                    Product_Name = "BunkerFO"
                    Product_Amount = gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & " คัน"
                Else
                    Product_Name &= "<br />" & "BunkerFO"
                    Product_Amount &= "<br />" & gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & " คัน"
                End If
            End If
            If (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & "" <> "") And (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & "" <> "0") Then
                If Product_Name = "" Then
                    Product_Name = "BunkerDO"
                    Product_Amount = gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & " คัน"
                Else
                    Product_Name &= "<br />" & "BunkerDO"
                    Product_Amount &= "<br />" & gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & " คัน"
                End If
            End If
            Dim File_Upload As String = ""

            If (gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload") & "" <> "") Then
                For i As Integer = 0 To gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",").Length - 1
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",")(i) & "" <> "") Then
                        If File_Upload = "" Then
                            File_Upload = gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",")(i)
                        Else
                            File_Upload &= "<br />" & gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",")(i)
                        End If
                    End If
                Next
            End If
            e.Row.Cells(6).Text = File_Upload
            e.Row.Cells(7).Text = Product_Name
            e.Row.Cells(8).Text = Product_Amount
            Dim Unit() As String = (gridItem.DataKeys(e.Row.RowIndex).Values("Product_Unit") & "").ToString.Split(",")
            Dim Text As String = ""
            For i As Integer = 0 To Unit.Length - 1
                If (Unit(i) & "" <> "") Then
                    If (Text = "") Then
                        Text = Unit(i)
                    Else
                        Text &= "<br />" & Unit(i)
                    End If
                End If
            Next
            e.Row.Cells(9).Text = Text
            Text = ""
            Unit = (gridItem.DataKeys(e.Row.RowIndex).Values("BUYER") & "").ToString.Split(",")
            For i As Integer = 0 To Unit.Length - 1
                If (Unit(i) & "" <> "") Then
                    If (Text = "") Then
                        Text = Unit(i)
                    Else
                        Text &= "<br />" & Unit(i)
                    End If
                End If
            Next
            e.Row.Cells(10).Text = Text
            Text = ""
            Unit = (gridItem.DataKeys(e.Row.RowIndex).Values("SELLER") & "").ToString.Split(",")
            For i As Integer = 0 To Unit.Length - 1
                If (Unit(i) & "" <> "") Then
                    If (Text = "") Then
                        Text = Unit(i)
                    Else
                        Text &= "<br />" & Unit(i)
                    End If
                End If
            Next
            e.Row.Cells(11).Text = Text
            If (clsFc.GetStatusCancel(gridItem.DataKeys(e.Row.RowIndex).Values("Status"))) Then
                e.Row.BackColor = Drawing.Color.Red
            Else
                Dim Product_Event As String = clsGet.Get_ProductEvent(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"))
                If (Product_Event = "L") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "O") Then
                        e.Row.BackColor = Drawing.Color.FromName("#6698FF")
                    Else
                        e.Row.BackColor = Drawing.Color.FromName("#A0CFEC")
                    End If
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "B") Then
                        e.Row.Cells(11).Text = Owner_name
                    End If
                ElseIf (Product_Event = "D") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "O") Then
                        e.Row.BackColor = Drawing.Color.FromName("#347C17")
                    Else
                        e.Row.BackColor = Drawing.Color.FromName("#52D017")
                    End If
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "B") Then
                        e.Row.Cells(10).Text = Owner_name
                    End If
                Else
                    e.Row.BackColor = Drawing.Color.White
                End If
            End If

            'Dim bookingNoLbtn As LinkButton = New LinkButton()
            'bookingNoLbtn = CType(e.Row.FindControl("LinkBooking"), LinkButton)
            'Dim bookingNo As String = bookingNoLbtn.Text
            LoadMergeBooking(e.Row)

        ElseIf (e.Row.RowType = DataControlRowType.Pager) Then
            Dim Page As GridViewRow = gridItem.BottomPagerRow
            Dim ddlPage As DropDownList = CType(e.Row.FindControl("ddlPage"), DropDownList)
            Dim lblPageCount As Label = CType(e.Row.FindControl("lbPageCount"), Label)
            If Not (ddlPage Is Nothing) Then
                For i As Integer = 0 To gridItem.PageCount - 1
                    Dim intPageNumber As Integer = i + 1
                    Dim IsItem As New ListItem(intPageNumber.ToString())
                    If (i = gridItem.PageIndex) Then
                        IsItem.Selected = True
                    End If
                    ddlPage.Items.Add(IsItem)
                Next
            End If
            If Not (lblPageCount Is Nothing) Then
                lblPageCount.Text = gridItem.PageCount.ToString()
            End If


            ' LoadMergeBooking(e)

        End If
    End Sub
    Protected Sub LoadMergeBooking(ByVal row As GridViewRow)
        Dim db As DB_Class = New DB_Class()
        Dim bookingNoLbtn As LinkButton = New LinkButton()
        bookingNoLbtn = CType(row.FindControl("LinkBooking"), LinkButton)
        Dim bookingNo As String = bookingNoLbtn.Text

        Dim drc As DataRowCollection = db.getTableWhere("Booking", "parentBookingRef='" + bookingNo + "'")

        If drc.Count > 0 Then
            Dim dr As DataRow = drc(0)
            Dim labelSeperate As Label = New Label()
            Dim hrTag As String = "<hr style='height:1px;background-color:#000;color:#000;pdding:0;margin:0'/>"
            ' Dim hrLiteral As LiteralControl = New LiteralControl(hr)
            labelSeperate.Text = "<br><br>&nbsp;&nbsp;&nbsp;&nbsp;"
            row.Cells(0).Controls.Add(labelSeperate)
            Dim lnkBtn As LinkButton = New LinkButton()
            lnkBtn.Text = dr("Booking_no").ToString()
            lnkBtn.CommandName = "Edit"
            lnkBtn.ID = "LinkBookingChild"
           
            'lnkBtn &= New GridViewCommandEventHandler(gridItem_RowCommand)
            lnkBtn.CommandArgument = row.RowIndex & ";" & dr("Booking_no").ToString()
            row.Cells(0).Controls.Add(lnkBtn)

            'Column Lay Time 
            row.Cells(5).Text += hrTag & dr("Lay_Time").ToString() & " hours"
            'Column COMMODITY Cells(7)
            row.Cells(7).Text += hrTag & dr("Product_Name").ToString()
            'Column QUANTITY
            row.Cells(8).Text += hrTag & dr("Product_Amount").ToString()
            'Column UNIT
            row.Cells(9).Text += hrTag & dr("Product_Unit").ToString()
            'Column BUYER
            row.Cells(10).Text += hrTag & dr("BUYER").ToString()
            'Column SALLER
            row.Cells(11).Text += hrTag & dr("SELLER").ToString()
            'Column Product
            row.Cells(13).Controls.Add(New LiteralControl(hrTag))
            Dim productStatusImg As Image = New Image()
            productStatusImg.ImageUrl = checkStatus(dr("MKT_Product"))
            row.Cells(13).Controls.Add(productStatusImg)

            'Column CUSTOM
            row.Cells(14).Controls.Add(New LiteralControl(hrTag))
            Dim customStatusImg As Image = New Image()
            customStatusImg.ImageUrl = checkStatus(dr("MKT_Custom"))
            row.Cells(14).Controls.Add(customStatusImg)

            'Column FINANCE
            row.Cells(15).Controls.Add(New LiteralControl(hrTag))
            Dim financeStatusImg As Image = New Image()
            financeStatusImg.ImageUrl = checkStatus(dr("MKT_Finance"))
            row.Cells(15).Controls.Add(financeStatusImg)

            'Column TERM & DEMURRAGE
            If (dr("Date_From") & "" <> "") Then
                'Column TERM
                If (dr("Vehicle_Destination") & "" = "O") Then
                    If (dr("Vehicle_TypeBuy") & "" = "F") Then
                        row.Cells(17).Text += hrTag & "FOB" 'รูปแบบการซื้อขาย
                    ElseIf (dr("Vehicle_TypeBuy") & "" = "C") Then
                        row.Cells(17).Text += hrTag & "CFR"
                    ElseIf (dr("Vehicle_TypeBuy") & "" = "I") Then
                        row.Cells(17).Text += hrTag & "CIF"
                    Else
                        row.Cells(17).Text += hrTag & "อื่นๆ" 'รูปแบบการซื้อขาย
                    End If
                Else
                    row.Cells(17).Text += hrTag & "" 'รูปแบบการซื้อขาย
                    row.Cells(16).Text += hrTag & ""
                End If
                ' Column DEMURRAGE
                If (dr("Demurrage_Money") & "" = "B") Then
                    If (dr("Demurrage") & "" = "") Then
                        row.Cells(16).Text += hrTag & "- BAHT"
                    Else
                        row.Cells(16).Text += hrTag & dr("Demurrage") & " BAHT "
                    End If
                ElseIf (dr("Demurrage_Money") & "" = "U") Then
                    If (dr("Demurrage") & "" = "") Then
                        row.Cells(16).Text += hrTag & "- USD"
                    Else
                        row.Cells(16).Text += hrTag & dr("Demurrage") & " USD "
                    End If
                End If
            End If

            Dim status As String = dr("Status").ToString()

            'Column PTMP
            Dim ptmpImgStatusUrl As String = ""
            If (dr("VPS_approve") & "" <> "") Then
                If (status = "VC") Or (status = "VP") Then 'imgVPS is PTMP
                    ptmpImgStatusUrl = "~/Image/red.png"
                Else
                    ptmpImgStatusUrl = "~/Image/green.png"
                End If
            Else
                ptmpImgStatusUrl = "~/Image/red.png"
            End If
            Dim ptmpImgStatus As Image = New Image()
            ptmpImgStatus.ImageUrl = ptmpImgStatusUrl
            row.Cells(18).Controls.Add(New LiteralControl(hrTag))
            row.Cells(18).Controls.Add(ptmpImgStatus)
            'Column PTMI

            Dim ptmiImgStatusUrl As String = ""
            If (dr("MRI_approve") & "" <> "") Then 'imgMRI is PTMI
                If (status = "MC") Or (status = "MP") Then
                    ptmiImgStatusUrl = "~/Image/red.png"
                Else
                    ptmiImgStatusUrl = "~/Image/green.png"
                End If
            Else
                If (status = "MO") Or (status = "OA") Or (status = "FN") Then
                    ptmiImgStatusUrl = "~/Image/green.png"
                Else
                    ptmiImgStatusUrl = "~/Image/red.png"
                End If
            End If
            row.Cells(19).Controls.Add(New LiteralControl(hrTag))
            Dim ptmiImgStatus As Image = New Image()
            ptmiImgStatus.ImageUrl = ptmiImgStatusUrl
            row.Cells(19).Controls.Add(ptmiImgStatus)

            'Column TARIFF
            Dim mktStatusImgUrl As String = ""
            If (dr("Payin") & "" = "0") Then
                Dim dt As DataTable = clsGet.Get_Booking_Gl_Account(bookingNo, dr("MAgent_no"))
                If (dt.Rows.Count > 0) Then
                    mktStatusImgUrl = "~/Image/green.png"
                Else
                    mktStatusImgUrl = "~/Image/red.png"
                End If
            ElseIf (dr("Marketing_approve") & "" = "") Then
                mktStatusImgUrl = "~/Image/red.png"
            Else
                mktStatusImgUrl = "~/Image/green.png"
            End If
            Dim mktStatusImg As Image = New Image()
            mktStatusImg.ImageUrl = mktStatusImgUrl
            row.Cells(20).Controls.Add(New LiteralControl(hrTag))
            row.Cells(20).Controls.Add(mktStatusImg)

            'Column AGENT
            Dim agentCell As TableCell = New TableCell()
            agentCell = row.Cells(21)
            Dim parentAgent As String = agentCell.Text
            agentCell.Text = "<span style='font-size:10px'>" & parentAgent & "</span>"
            agentCell.Text += hrTag & "<span  style='font-size:10px'>" & dr("MAgent_name") & "</span>"

            'Column CONFIRM PLAN BERTH Cells(27)
            Dim imgConfrim As Image = New Image()
            If (gridItem.DataKeys(row.RowIndex).Values("Confirm_Time") & "" = "Y") Then
                imgConfrim.ImageUrl = "~/Image/4558.png"
            Else
                imgConfrim.ImageUrl = "~/Image/4557.gif"
            End If
            row.Cells(27).Controls.Add(New LiteralControl(hrTag))
            row.Cells(27).Controls.Add(imgConfrim)
            'Column Detail Cells(30)
            row.Cells(30).Controls.Add(New LiteralControl(hrTag))
            Dim detailLinkBtn As LinkButton = New LinkButton()
            detailLinkBtn.Text = "Detail"
            detailLinkBtn.CssClass = "ButtonStyle linkBtn"
            detailLinkBtn.CommandName = "Detail"
            detailLinkBtn.CommandArgument = row.RowIndex & ";" & dr("Booking_no").ToString()
            row.Cells(30).Controls.Add(detailLinkBtn)
        End If

        
    End Sub
    Protected Function checkStatus(ByVal status As String)
        Dim productStatusImgUrl As String = ""
        If status = "Y" Then
            productStatusImgUrl = "~/Image/green.png"
        Else
            productStatusImgUrl = "~/Image/red.png"
        End If
        Return productStatusImgUrl
    End Function

    Public Function CreateDatasetProduct() As DataTable
        Dim ds As New DataSet
        Dim dt As New DataTable
        Dim dr As DataRow
        ds.Tables.Add(dt)
        dt.Columns.Add("Product_no", GetType(String))
        dt.Columns.Add("Product_name", GetType(String))
        dt.Columns.Add("Product_Amount", GetType(String))
        dt.Columns.Add("Product_Event", GetType(String))
        dt.Columns.Add("Product_Description", GetType(String))
        dt.Columns.Add("Product_Unit", GetType(String))
        dt.Columns.Add("Group_name", GetType(String))
        dt.Columns.Add("Group_no", GetType(String))
        dt.Columns.Add("Product_BUYER_no", GetType(String))
        dt.Columns.Add("Product_BUYER_name", GetType(String))
        dt.Columns.Add("Product_SELLER_no", GetType(String))
        dt.Columns.Add("Product_SELLER_name", GetType(String))
        dt.Columns.Add("LoadDestination", GetType(String))
        dt.Columns.Add("DischDestination", GetType(String))
        dt.Columns.Add("DestinationShow", GetType(String))
        dt.Columns.Add("Owner_Product_no", GetType(String))
        dt.Columns.Add("Owner_Product_name", GetType(String))
        dr = ds.Tables(0).NewRow
        dr.Item("Product_no") = ""
        dr.Item("Product_name") = ""
        dr.Item("Product_Amount") = ""
        dr.Item("Product_Event") = ""
        dr.Item("Product_Description") = ""
        dr.Item("Product_Unit") = ""
        dr.Item("Group_name") = ""
        dr.Item("Group_no") = ""
        dr.Item("Product_BUYER_no") = ""
        dr.Item("Product_BUYER_name") = ""
        dr.Item("Product_SELLER_no") = ""
        dr.Item("Product_SELLER_name") = ""
        dr.Item("LoadDestination") = ""
        dr.Item("DischDestination") = ""
        dr.Item("DestinationShow") = ""
        dr.Item("Owner_Product_no") = ""
        dr.Item("Owner_Product_name") = ""
        ds.Tables(0).Rows.Add(dr)
        ds.Tables(0).AcceptChanges()
        Return ds.Tables(0)
    End Function

    Private Sub btnProduct_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnProduct.Click
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_ProductPopup').src = '../FormPopup/ProductPopup.aspx';", True)
        Session("PORT_PRODUCT") = radioPort.SelectedValue
        ModalPopupExtender5.Show()
    End Sub

    Private Sub gridProduct_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridProduct.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If e.CommandName = "cmddelete" Then
            Dim ds As DataTable = Session("Product_popup")
            ds.Rows(Index).Delete()
            ds.AcceptChanges()
            If (ds.Rows.Count = 0) Then
                ds = CreateDatasetProduct()
            End If
            Session("Product_popup") = ds
            gridProduct.PageIndex = 0
            gridProduct.DataSource = Session("Product_popup")
            gridProduct.DataBind()
        ElseIf e.CommandName = "cmdedit" Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_ProductPopup').src = '../FormPopup/ProductPopup.aspx';", True)
            Session("IndexProduct") = Index
            Session("PORT_PRODUCT") = radioPort.SelectedValue
            ModalPopupExtender5.Show()
        End If
    End Sub

    Private Sub gridProduct_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridProduct.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim ImgDelete As ImageButton = CType(e.Row.FindControl("imgdelete"), ImageButton)
            Dim ImgEdit As ImageButton = CType(e.Row.FindControl("imgedit"), ImageButton)
            'Dim dt As DataTable = clsGet.Get_Booking_Product(ViewState("EditBooking"))
            'For Each dr As DataRow In dt.Rows
            '    If (dr.Item("Product_no") = gridProduct.DataKeys(e.Row.RowIndex).Values("Product_no")) Then
            '        ImgDelete.Visible = False
            '        Exit For
            '    End If
            'Next
            If (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_name") & "" = "") Then
                ImgDelete.Visible = False
                ImgEdit.Visible = False
            End If
            'If (ViewState("EditBooking") & "" <> "") Then
            '    ImgDelete.Visible = False
            '    ImgEdit.Visible = False
            'End If
            If (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "L") Then
                e.Row.Cells(0).Text = "Load"
            ElseIf (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "D") Then
                e.Row.Cells(0).Text = "Disch"
            ElseIf (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "R") Then
                e.Row.Cells(0).Text = "Load(IRPC)"
            ElseIf (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "I") Then
                e.Row.Cells(0).Text = "Disch(IRPC)"
            End If
            If (gridProduct.DataKeys(e.Row.RowIndex).Values("Group_no") & "" = "0000000000") Then
                e.Row.BackColor = Drawing.Color.Red
            End If
        End If
    End Sub

    Private Sub gridItem_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridItem.RowCreated
        If e.Row.RowType = DataControlRowType.Header Then
            Dim Grid As GridView = CType(sender, GridView)
            e.Row.Cells.Clear()
            Dim GridRow As GridViewRow = New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert)
            Dim GridRow1 As GridViewRow = New GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert)

            Dim table As TableCell = New TableCell()
            table.Text = "BOOKING NO."
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.CssClass = "locked"
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "VESSEL NAME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.CssClass = "locked"
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "STATUS"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "LAY CAN/LAY DAY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "REQUIRE DATE/TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "LAY TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "ATTACHMENT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "COMMODITY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "QUANTITY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "UNIT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "BUYER"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)


            table = New TableCell()
            table.Text = "SELLER"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "APPROVE BY MKT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.ColumnSpan = 5
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "APPROVE BY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.ColumnSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "TARIFF"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "AGENT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "WHARF"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN BERTH DATE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN BERTH TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN DEPART DATE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN DEPART TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "CONFIRM PLAN BERTH"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "REMAIN LAYTIME(ESTIMATE)"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "REMARK"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = ""
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            Grid.Controls(0).Controls.AddAt(0, GridRow1)

            table = New TableCell()
            table.Text = "PRODUCT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "CUSTOM"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "FINANCE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "DEMURRAGE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "TERM"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "PTMP"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "PTMI"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            Grid.Controls(0).Controls.AddAt(1, GridRow)
        ElseIf e.Row.RowType = DataControlRowType.DataRow Then
           
        End If
    End Sub

    Private Sub raioType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles raioType.SelectedIndexChanged
        If raioType.SelectedValue = "O" Then
            rowTypeBuy.Visible = True
        Else
            rowTypeBuy.Visible = False
        End If
    End Sub

    Private Sub btnComputeTariff_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnComputeTariff.Click
        If ComputeMAT() Then
            ComputeTariff.Visible = False
            rowGridTariff.Visible = True
            btnCompute.Visible = True
        End If
    End Sub

    Private Function ComputeMAT() As Boolean
        If (CheckParameter()) Then
            If (CDate(txtDate.Text) > CDate(txtDateTo.Text)) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ข้อมูลวันที่เข้า ไม่ถูกต้อง!!');", True)
                Return False
            End If
            If (chkFO.Checked) Then
                If (txtFO.Text.Trim() = "") Or (txtFO.Text.Trim() = "0") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาระบุจำนวนคันรถของ Bunker FO !!');", True)
                    Return False
                End If
            End If
            If (chkDO.Checked) Then
                If (txtDO.Text.Trim() = "") Or (txtDO.Text.Trim() = "0") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาระบุจำนวนคันรถของ Bunker DO !!');", True)
                    Return False
                End If
            End If
            If (txtid.Text.Split("-")(0) = "999999999") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่สามารถให้ IRPC เป็น Main Agent ได้ !!');", True)
                Return False
            End If
            If (txtAgent.Text.Split("-")(0) = "999999999") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่สามารถให้ IRPC เป็น Sub Agent ได้  !!');", True)
                Return False
            End If
            Dim National As String = ""
            Dim TypeBuy As String = ""
            If (radioVehicle.SelectedValue = "I") Then
                National = "T"
            Else
                National = "O"
                TypeBuy = radioTypeBuy.SelectedValue
            End If
            Dim Load As String = ""
            Dim Disch As String = ""
            Dim MaterailB As String = ""
            Dim VesselNation As String = ""
            Dim dt As DataTable = Session("Product_popup")
            For Each dr As DataRow In dt.Rows
                Dim sLoad As String = ""
                Dim sDisch As String = ""
                Dim sLoadIRPC As String = ""
                Dim sDischIRPC As String = ""
                Select Case dr.Item("Product_Event") & ""
                    Case "L" : Load = "Y"
                        sLoad = "Y"
                    Case "D" : Disch = "Y"
                        sDisch = "Y"
                End Select
                'If (raioType.SelectedValue = "O") Then
                '    Session("Operation") = Load & "$" & Disch & "$" & LoadIRPC & "$" & DischIRPC & "$" & raioType.SelectedValue & "$" & radioTypeBuy.SelectedValue
                'Else
                '    Session("Operation") = Load & "$" & Disch & "$" & LoadIRPC & "$" & DischIRPC & "$" & raioType.SelectedValue & "$" & ""
                'End If

                Dim dtMat As DataTable = clsGet.Get_Meterail_ProductMaterial(dr.Item("Product_no"), sLoad, sDisch, sLoadIRPC, sDischIRPC)
                For Each drMat As DataRow In dtMat.Rows
                    If (drMat.Item("Material") <> "") Then
                        MaterailB = ",'" & drMat.Item("Material") & "'"
                    End If
                Next
            Next
            If (radioVehicle.SelectedValue = "0") Then
                If lbNation.Text = "TH" Then
                    VesselNation = "T"
                Else
                    VesselNation = "O"
                End If
            Else
                VesselNation = ddlNation.SelectedValue
            End If
            If (radioPort.SelectedValue = "B") Then
                Dim Productchk As Boolean = True
                If (gridProduct.Rows.Count < 2) Then
                    Try
                        If (gridProduct.DataKeys(0).Item("Product_no") & "" = "") Then
                            Productchk = False
                        End If
                    Catch ex As Exception
                        Productchk = False
                    End Try
                End If
                If (Productchk) Then
                    Dim Owner() As String = ViewState("OwnerColumn").ToString.Split("$")
                    For i As Integer = 0 To Owner.Length - 1
                        gridTariff.Columns(4 + i).Visible = True
                        gridTariff.Columns(4 + i).HeaderText = Owner(i).Split("฿")(1)
                    Next
                    btnProduct.Enabled = False
                    gridProduct.Columns(11).Visible = False
                End If

            End If
            LoadDefault_MAT(National, TypeBuy, Load, Disch, MaterailB, VesselNation)
            If (Session("Role") & "" = "00002") Then
                txtDate.Enabled = False
                ImgDate.Enabled = False
                txtDateTo.Enabled = False
                ImgDateTo.Enabled = False
                txtDateBooking.Enabled = False
                txtTimeBooking.Enabled = False
                btnProduct.Enabled = False
            End If

            Return True
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุข้อมูลให้ครบ!!');", True)
            Return False
        End If
    End Function

    Private Sub radioPort_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioPort.SelectedIndexChanged
        postBackClick.Value = "1"
        If (radioPort.SelectedValue = "") Then
            PanelVessel.Visible = False
        Else
            PanelVessel.Visible = True
            Session("PORT_PRODUCT") = radioPort.SelectedValue
            If (radioPort.SelectedValue = "L") Then
                gridProduct.Columns(5).Visible = True
                gridProduct.Columns(6).Visible = True
                gridProduct.Columns(7).Visible = False
            Else
                gridProduct.Columns(5).Visible = False
                gridProduct.Columns(6).Visible = False
                gridProduct.Columns(7).Visible = True
            End If
        End If
    End Sub

    Public Function CreateFileDataTable() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("File_nameGuid", GetType(String))
        dt.Columns.Add("File_name", GetType(String))
        dt.Columns.Add("File_Type", GetType(String))
        dt.Columns.Add("File_ContentType", GetType(String))
        dt.Columns.Add("Upload_Type", GetType(String))
        dt.Columns.Add("Description", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Private Sub btnSaveUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveUpload.Click
        gridfile.DataSource = Session("Q88")
        gridfile.DataBind()
    End Sub

    Private Sub gridfile_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridfile.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (e.CommandName = "cmddelete") Then
            Dim dt As DataTable = Session("Q88")
            System.IO.File.Delete(Server.MapPath("../Uploads/") + dt.Rows(Index).Item("File_nameGuid"))
            dt.Rows(Index).Delete()
            dt.AcceptChanges()
            Session("Q88") = dt
            gridfile.DataSource = dt
            gridfile.DataBind()
        ElseIf (e.CommandName = "Select") Then
            Dim FileName As String = gridfile.DataKeys(Index).Values("File_name")
            Dim FileGen As String = gridfile.DataKeys(Index).Values("File_nameGuid") & gridfile.DataKeys(Index).Values("File_Type")
            ' Dim FileType As String = gridfile.DataKeys(Index).Values("File_Type")
            Dim ContentType As String = gridfile.DataKeys(Index).Values("File_ContentType").ToString().Replace(".", "")

            Dim script As String = "window.open('IPORTDownloadfile.aspx?str2=" + FileGen + "&str3=." + ContentType + "&str4=" + FileName + "','_blank','left=0,top=0,location=no,menubar= no,resizable=yes,scrollbars=no,toolbar=no,status=no,width=100px,height=50px');"
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", script, True)
        End If
    End Sub

    Private Sub btnSaveProduct_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveProduct.Click
        Dim dt As DataTable = Session("Product_popup")
        If (dt.Rows.Count > 0) Then
            If (txtid.Text.Trim() <> "") Then
                Dim name() As String = txtid.Text.Split("-")
                Dim soldto As String = txtid.Text.Split("-")(0) & "฿"
                For i As Integer = 1 To name.Length - 1
                    soldto &= name(i) & " "
                Next
                ViewState("OwnerColumn") = soldto
            Else
                ViewState("OwnerColumn") = "฿Sold To"
            End If
            If (dt.Rows(0).Item("Product_Event") & "" = "L") Or (dt.Rows(0).Item("Product_Event") & "" = "R") Then
                lbType.Text = "DISCHARGING PORT"
                gridProduct.Columns(8).HeaderText = "DISCHARGING PORT"
            Else
                lbType.Text = "LOADING PORT"
                gridProduct.Columns(8).HeaderText = "LOADING PORT"
            End If
        End If
        If (radioPort.SelectedValue = "B") Then
            'Bulk
            For Each dr As DataRow In dt.Rows
                If (dr.Item("Owner_Product_no") & "" <> "") Then
                    Dim chk() As String = ViewState("OwnerColumn").ToString.Split("$")
                    Dim chkDuplicate As Boolean = True
                    For i As Integer = 0 To chk.Length - 1
                        If (chk(i) = dr.Item("Owner_Product_name") & "") Then
                            chkDuplicate = False
                        End If
                    Next
                    If (chkDuplicate) Then
                        ViewState("OwnerColumn") &= "$" & dr.Item("Owner_Product_no") & "฿" & dr.Item("Owner_Product_name")
                    End If
                End If
            Next
        Else
        'Liquid ไม่มีเจ้าของสินค้า
        ViewState("OwnerColumn") = ""
        End If
        gridProduct.DataSource = dt
        gridProduct.DataBind()
    End Sub

    Private Sub gridProduct_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridProduct.RowEditing

    End Sub

    'Private Sub btnSubAgent_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubAgent.Click
    '    If (txtid.Text.Trim <> "") Then
    '        If ((clsGet.Get_Customer(txtid.Text.Trim().Split("-")(0))).Rows.Count < 1) Then
    '            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Sub Agent !!');", True)
    '            Exit Sub
    '        End If
    '    End If
    '    If (txtAgent.Text.Trim <> "") Then
    '        If ((clsGet.Get_Customer(txtAgent.Text.Trim().Split("-")(0))).Rows.Count < 1) Then
    '            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Main Agent !!');", True)
    '            Exit Sub
    '        End If
    '    End If
    '    If (txtid.Text.Trim <> "") Or (txtAgent.Text.Trim <> "") Then
    '        Dim MAgent_no As String = ""
    '        Dim MAgent_name As String = ""
    '        Dim SAgent_no As String = ""
    '        Dim SAgent_name As String = ""
    '        If (txtid.Text.Trim() <> "") Then
    '            MAgent_no = txtid.Text.Split("-")(0)
    '            Dim AgentLoop() As String = txtid.Text.Split("-")
    '            For i As Integer = 0 To AgentLoop.Length - 1
    '                If (i <> 0) Then
    '                    MAgent_name &= "-" & AgentLoop(i).ToString()
    '                End If
    '            Next
    '            MAgent_name = MAgent_name.Substring(1, MAgent_name.Length - 1)
    '        End If
    '        If (txtAgent.Text.Trim() <> "") Then
    '            SAgent_no = txtAgent.Text.Split("-")(0)
    '            Dim AgentLoop() As String = txtAgent.Text.Split("-")
    '            For i As Integer = 0 To AgentLoop.Length - 1
    '                If (i <> 0) Then
    '                    SAgent_name &= "-" & AgentLoop(i).ToString()
    '                End If
    '            Next
    '            SAgent_name = SAgent_name.Substring(1, SAgent_name.Length - 1)
    '        End If

    '        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
    '        Dim clsDB As New ClassDatabase
    '        Dim clsFc As New ClassFunction
    '        Dim condition As Boolean = True
    '        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
    '        Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
    '        Dim Vps As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
    '        Application.Lock()
    '        conn.Open()

    '        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
    '        tran = clsDB.BeginTran(conn)
    '        Try

    '            If (clsFc.UpdateBookingAgent(ViewState("EditBooking"), MAgent_no, MAgent_name, SAgent_no, SAgent_name, conn, tran) > 0) Then
    '                If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), ds_Log.Rows(0).Item("Status"), txtRemark.Text, Vps, "", "", "", ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), MAgent_no, MAgent_name, SAgent_no, SAgent_name, ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), ds_Log.Rows(0).Item("MKT_Approve"), ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), ds_Log.Rows(0).Item("MKT_Acknowledge"), ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", ds_Log.Rows(0).Item("Shifting") & "", conn, tran) < 1) Then
    '                    condition = False
    '                End If
    '            End If
    '            If (condition) Then
    '                clsDB.CommitTran(tran)
    '                If (txtid.Text.Trim() <> "") Then
    '                    txtid.Enabled = False
    '                End If
    '                If (txtAgent.Text.Trim() <> "") Then
    '                    txtAgent.Enabled = False
    '                End If
    '                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูล Agent สำเร็จ');", True)
    '            Else
    '                clsDB.RollBackTran(tran)
    '                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
    '            End If
    '        Catch ex As Exception
    '            clsDB.RollBackTran(tran)
    '            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
    '        End Try
    '        Application.UnLock()
    '        conn.Dispose()
    '    Else
    '        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Main Agent หรือ Sub Agent ก่อนทำการ Update !!');", True)
    '    End If

    'End Sub

    Private Sub btnSaveCancelBooking_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveCancelBooking.Click
        Dim Status As String = "CC"
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
        Dim Customer_Action As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
        Dim Cancel_Description As String = Session("Cancel_Description")
        Session("Cancel_Description") = Nothing
        Application.Lock()
        conn.Open()

        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
        tran = clsDB.BeginTran(conn)
        Try

            If (clsFc.UpdateCancelBooking(ViewState("EditBooking"), Status, Customer_Action, Cancel_Description, "", conn, tran) > 0) Then
                If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), ds_Log.Rows(0).Item("Status"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_Approve"), ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_Approve"), ds_Log.Rows(0).Item("Marketing_Approve"), ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), "", Customer_Action, Cancel_Description, "", "", ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", ds_Log.Rows(0).Item("Shifting") & "", conn, tran) < 1) Then
                    condition = False
                End If
            End If
            If (condition) Then
                clsDB.CommitTran(tran)

                Dim MAgent_no As String = ""
                Dim MAgent_name As String = ""
                Dim Vehicle As String = ""
                Dim Vehicle_Name As String = ""
                If (txtid.Text.Trim = "") Then
                    MAgent_no = ""
                    MAgent_name = ""
                Else
                    MAgent_no = txtid.Text.Split("-")(0)
                    ' MAgent_name = txtid.Text.Split("-")(1)
                    Dim AgentLoops() As String = txtid.Text.Split("-")
                    For i As Integer = 0 To AgentLoops.Length - 1
                        If (i <> 0) Then
                            MAgent_name &= "-" & AgentLoops(i).ToString()
                        End If
                    Next
                    MAgent_name = MAgent_name.Substring(1, MAgent_name.Length - 1)
                End If
                If (radioVehicle.SelectedValue = "0") Then
                    Vehicle = txtVessel.Text.Split("-")(0)
                    '  Vehicle_Name = txtVessel.Text.Split("-")(1)
                    Dim AgentLoops() As String = txtVessel.Text.Split("-")
                    For i As Integer = 0 To AgentLoops.Length - 1
                        If (i <> 0) Then
                            Vehicle_Name &= "-" & AgentLoops(i).ToString()
                        End If
                    Next
                    Vehicle_Name = Vehicle_Name.Substring(1, Vehicle_Name.Length - 1)
                Else
                    Vehicle = "999999999"
                    Vehicle_Name = txtVesselOUT.Text.Trim()
                End If
                SendMail(GenBody("รายการจองได้ถูกทำการยกเลิก กรุณาทำการตรวจสอบข้อมูลผ่านระบบ iPORT", ViewState("EditBooking"), MAgent_no & "-" & MAgent_name, Vehicle & "-" & Vehicle_Name, txtDate.Text & "-" & txtDateTo.Text))
                ViewState("EditBooking") = ""
                Session("Product_popup") = CreateDatasetProduct()
                PanelBookingItem.Visible = True
                PanelBooking.Visible = False
                ClearData()
                ShowPanelForRole()
                ViewState("Load") = "Not"

                Timer1_Tick(sender, e)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการยกเลิกรายการจองสำเร็จ ');", True)
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
            End If
        Catch ex As Exception
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
        End Try
        Application.UnLock()
        conn.Dispose()
    End Sub


    Private Function UpdateVessel(ByVal Vehicle As String) As Boolean
        Dim ClassSAP As New Class_SAP
        Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
        Dim dsConfig As DataSet = Session("Config")
        Dim Im_Veh_From As String = Vehicle
        Dim Im_Veh_To As String = ""
        Dim Date_From As String = ""
        Dim Date_To As String = ""

        Dim Ex_Subrc As Integer = 0

        Dim Veh_Table As New SAP_IPORT.ZBAPI_VEH_INPUTTable
        Dim Veh_Infor As New SAP_IPORT.ZBAPI_VEH_INFORTable
        Dim Veh_Unit As New SAP_IPORT.ZBAPI_VEH_UNITTable
        SAP_Data.Zbapi_Iport_Vehicle_Master(Date_From, Date_To, Im_Veh_From, Im_Veh_To, Ex_Subrc, Veh_Table, Veh_Infor, Veh_Unit)
        ClassSAP.SAP_CLOSE(SAP_Data)
        If (Veh_Unit.Count > 0) Or (Veh_Infor.Count > 0) Then
            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
            Dim clsDB As New ClassDatabase()
            Dim clsFc As New ClassFunction()
            Dim condition As Boolean = True
            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
            Try

                Application.Lock()
                conn.Open()
                tran = clsDB.BeginTran(conn)
                For i As Integer = 0 To Veh_Infor.Count - 1
                    If (clsFc.UPDATEVehicle(Veh_Infor.Item(i).Vehicle, Veh_Infor.Item(i).Veh_Text, Veh_Infor.Item(i).Owner, Veh_Infor.Item(i).Reg_Cntry, Veh_Infor.Item(i).Veh_Type, Veh_Infor.Item(i).Veh_Length, Veh_Infor.Item(i).Veh_Width, Veh_Infor.Item(i).Veh_Height, Veh_Infor.Item(i).Draft, Veh_Infor.Item(i).Dim_Uom, Veh_Infor.Item(i).Veh_Unlwgt, Veh_Infor.Item(i).Veh_Unlwgt_C, Veh_Infor.Item(i).Veh_Maxwgt, Veh_Infor.Item(i).Veh_Maxwgt_C, Veh_Infor.Item(i).Wgt_Uom, Veh_Infor.Item(i).Veh_Maxvol, Veh_Infor.Item(i).Veh_Maxvol_C, Veh_Infor.Item(i).Vol_Uom, Veh_Infor.Item(i).Stcmnr, Veh_Infor.Item(i).Veh_Nrtus, conn, tran) = 0) Then
                        If (clsFc.InsertVehicle(Veh_Infor.Item(i).Vehicle, Veh_Infor.Item(i).Veh_Text, Veh_Infor.Item(i).Owner, Veh_Infor.Item(i).Reg_Cntry, Veh_Infor.Item(i).Veh_Type, Veh_Infor.Item(i).Veh_Length, Veh_Infor.Item(i).Veh_Width, Veh_Infor.Item(i).Veh_Height, Veh_Infor.Item(i).Draft, Veh_Infor.Item(i).Dim_Uom, Veh_Infor.Item(i).Veh_Unlwgt, Veh_Infor.Item(i).Veh_Unlwgt_C, Veh_Infor.Item(i).Veh_Maxwgt, Veh_Infor.Item(i).Veh_Maxwgt_C, Veh_Infor.Item(i).Wgt_Uom, Veh_Infor.Item(i).Veh_Maxvol, Veh_Infor.Item(i).Veh_Maxvol_C, Veh_Infor.Item(i).Vol_Uom, Veh_Infor.Item(i).Stcmnr, Veh_Infor.Item(i).Veh_Nrtus, conn, tran) < 1) Then
                            condition = False
                        End If
                    End If
                Next
                For i As Integer = 0 To Veh_Unit.Count - 1
                    If (clsFc.UPDATEVehicle_infor(Veh_Unit.Item(i).Vehicle, Veh_Unit.Item(i).Tu_Type, Veh_Unit.Item(i).Tu_Class, Veh_Unit.Item(i).Tu_Mode, Veh_Unit.Item(i).Tu_Length, Veh_Unit.Item(i).Tu_Width, Veh_Unit.Item(i).Tu_Height, Veh_Unit.Item(i).Dim_Uom, Veh_Unit.Item(i).Tu_Unlwgt, Veh_Unit.Item(i).Tu_Unlwgt_C, Veh_Unit.Item(i).Tu_Maxwgt, Veh_Unit.Item(i).Tu_Maxwgt_C, Veh_Unit.Item(i).Wgt_Uom, Veh_Unit.Item(i).Tu_Maxvol, Veh_Unit.Item(i).Tu_Maxvol_C, Veh_Unit.Item(i).Vol_Uom, conn, tran) = 0) Then
                        If (clsFc.InsertVehicle_infor(Veh_Unit.Item(i).Vehicle, Veh_Unit.Item(i).Tu_Type, Veh_Unit.Item(i).Tu_Class, Veh_Unit.Item(i).Tu_Mode, Veh_Unit.Item(i).Tu_Length, Veh_Unit.Item(i).Tu_Width, Veh_Unit.Item(i).Tu_Height, Veh_Unit.Item(i).Dim_Uom, Veh_Unit.Item(i).Tu_Unlwgt, Veh_Unit.Item(i).Tu_Unlwgt_C, Veh_Unit.Item(i).Tu_Maxwgt, Veh_Unit.Item(i).Tu_Maxwgt_C, Veh_Unit.Item(i).Wgt_Uom, Veh_Unit.Item(i).Tu_Maxvol, Veh_Unit.Item(i).Tu_Maxvol_C, Veh_Unit.Item(i).Vol_Uom, conn, tran) < 1) Then
                            condition = False
                        End If
                    End If

                Next
                If (Date_To <> "") Then
                    If (clsFc.UpdateVehicle_Date(Date_To, conn, tran) < 1) Then
                        condition = False
                    End If
                End If

                If (condition) Then
                    clsDB.CommitTran(tran)
                    conn.Close()
                    Application.UnLock()
                    Veh_Infor.Clear()
                    Veh_Unit.Clear()
                    conn.Dispose()

                    Return True
                Else
                    clsDB.RollBackTran(tran)
                    conn.Close()
                    Application.UnLock()
                    Veh_Infor.Clear()
                    Veh_Unit.Clear()
                    conn.Dispose()
                    Return False
                End If
            Catch ex As Exception
                clsDB.RollBackTran(tran)
                conn.Close()
                Application.UnLock()
                Veh_Infor.Clear()
                Veh_Unit.Clear()
                conn.Dispose()
                Return False
            End Try

        Else
            Return True
        End If
    End Function

    Private Sub radioDemurrage_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioDemurrage.SelectedIndexChanged
        If (radioDemurrage.SelectedValue = "Y") Then
            rowLaytime.Visible = True
            txtDemurrage.Text = "0"
            txtLayTime.Text = "0"
        Else
            rowLaytime.Visible = False
            txtDemurrage.Text = "0"
            txtLayTime.Text = "0"
        End If
    End Sub

    Private Function GetNameMonth(ByVal Month As String) As String
        Try
            Select Case (CInt(Month).ToString("00"))
                Case "01"
                    Return "Jan"
                Case "02"
                    Return "Feb"
                Case "03"
                    Return "Mar"
                Case "04"
                    Return "Apr"
                Case "05"
                    Return "May"
                Case "06"
                    Return "Jun"
                Case "07"
                    Return "Jul"
                Case "08"
                    Return "Aug"
                Case "09"
                    Return "Sep"
                Case "10"
                    Return "Oct"
                Case "11"
                    Return "Nov"
                Case "12"
                    Return "Dec"
                Case Else
                    Return ""
            End Select
        Catch ex As Exception
            Return Month
        End Try

    End Function

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If (ViewState("Load") & "" <> "Not") Then
            ShowPanelForRole()
        Else
            ViewState("Load") = ""
        End If
        For i As Integer = 0 To gridItem.Rows.Count - 1
            Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(gridItem.DataKeys(i).Values("Booking_no"))
            If (dsBooking.Tables(0).Rows(0).Item("Lay_Time") & "" <> "0") Then
                Dim dtLogIn As DataTable = clsGet.Get_Booking_LogSheet_In(gridItem.DataKeys(i).Values("Booking_no"))
                If Not (dtLogIn.Rows.Count = 0) Then
                    If Not (dtLogIn.Rows(0).Item("Berthing_Date") & "" = "") Or (dtLogIn.Rows(0).Item("Berthing_TimeTo") & "" = "") Then
                        If Not (dtLogIn.Rows(0).Item("POB_Date") & "" = "") Or (dtLogIn.Rows(0).Item("POB_Time") & "" = "") Then
                            Dim dtProduct As DataTable = clsGet.Get_Booking_Product(gridItem.DataKeys(i).Values("Booking_no"))
                            If Not (dtProduct.Rows.Count = 0) Then
                                If (dsBooking.Tables(0).Rows(0).Item("PORT") & "" = "L") Then
                                    Dim Product_no As String = ""
                                    Try
                                        Dim sort As Integer = 0
                                        For Each dr As DataRow In dtProduct.Rows
                                            If (CInt(dr.Item("Product_Index") & "") > sort) Then
                                                sort = CInt(dr.Item("Product_Index"))
                                                Product_no = dr.Item("Product_no")
                                            End If
                                        Next
                                    Catch ex As Exception

                                    End Try
                                    Dim dtLoad As DataTable = clsGet.Get_Load_Unload_Vessel(gridItem.DataKeys(i).Values("Booking_no"))
                                    Dim NOR As String = ""
                                    Dim NOR_Time As String = ""
                                    Dim POB As String = ""
                                    Dim POB_Time As String = ""
                                    If (dtLoad.Rows.Count > 0) Then
                                        If (dtLoad.Rows(0).Item("NOR_Date") & "" <> "") Then
                                            NOR = dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(3, 2)) & " 20" & dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(6, 2)
                                            NOR_Time = dtLoad.Rows(0).Item("NOR_Time") & ""
                                        Else
                                            NOR = dtLogIn.Rows(0).Item("NOR_Date") & ""
                                            NOR_Time = dtLogIn.Rows(0).Item("NOR_Time") & ""
                                        End If
                                    Else
                                        NOR = dtLogIn.Rows(0).Item("NOR_Date") & ""
                                        NOR_Time = dtLogIn.Rows(0).Item("NOR_Time") & ""
                                    End If
                                    If (dtLogIn.Rows(0).Item("POB_Date") & "" <> "") Then
                                        If (dtLogIn.Rows(0).Item("Up_Date") & "" <> "") Then
                                            If (CDate(dtLogIn.Rows(0).Item("POB_Date")) < CDate(dtLogIn.Rows(0).Item("Up_Date"))) Then
                                                POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                                POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                            ElseIf (CDate(dtLogIn.Rows(0).Item("POB_Date")) = CDate(dtLogIn.Rows(0).Item("Up_Date"))) Then
                                                If (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(0)) < CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(0))) Then
                                                    POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                                    POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                                ElseIf (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(0)) = CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(0))) Then
                                                    If (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(1)) < CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(1))) Then
                                                        POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                                        POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                                    Else
                                                        POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                                        POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                                    End If
                                                Else
                                                    POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                                    POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                                End If
                                            Else
                                                POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                                POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                            End If
                                        Else
                                            POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                            POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                        End If
                                    Else
                                        POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                        POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                    End If

                                    dtLoad = clsGet.Get_Load_Unload_Product(gridItem.DataKeys(i).Values("Booking_no"), Product_no)
                                    Dim Dis_Date As String = ""
                                    Dim Dis_Time As String = ""
                                    For Each dl As DataRow In dtLoad.Rows
                                        Try
                                            If (Dis_Date = "") Then
                                                Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                            End If
                                            Dim _DD As String = Dis_Date.Substring(0, 2) & " " & GetNameMonth(Dis_Date.Substring(3, 2)) & " " & CInt("20" & Dis_Date.Substring(6, 2))
                                            Dim _D2 As String = dl.Item("LU_Disconnect_Date").Substring(0, 2) & " " & GetNameMonth(dl.Item("LU_Disconnect_Date").Substring(3, 2)) & " " & CInt("20" & dl.Item("LU_Disconnect_Date").Substring(6, 2))
                                            If (CDate(_DD) < CDate(_D2)) Then
                                                Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                            ElseIf (CDate(_DD) = CDate(_D2)) Then
                                                If (CInt(Dis_Time.Split(":")(0)) < CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(0))) Then
                                                    Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                    Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                                ElseIf (CInt(Dis_Time.Split(":")(0)) = CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(0))) Then
                                                    Try
                                                        If (CInt(Dis_Time.Split(":")(1)) < CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(1))) Then
                                                            Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                            Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                                        End If
                                                    Catch ex As Exception

                                                    End Try
                                                End If
                                            End If
                                        Catch ex As Exception

                                        End Try

                                    Next
                                    Dim Berthing_Date As String = dtLogIn.Rows(0).Item("Berthing_Date")
                                    Try
                                        Try
                                            If (CInt(dtLogIn.Rows(0).Item("Berthing_TimeTo").ToString().Split(":")(0)) < CInt(dtLogIn.Rows(0).Item("Berthing_TimeFrom").ToString.Split(":")(0))) Then
                                                Berthing_Date = CDate(Berthing_Date).AddDays(1).ToString("dd MMM", New CultureInfo("en-US")) & " " & Berthing_Date.Split(" ")(2)
                                            End If
                                        Catch ex As Exception

                                        End Try
                                    Catch ex As Exception

                                    End Try
                                    If (dtLoad.Rows.Count > 0) Then
                                        gridItem.Rows(i).Cells(28).Text = clsGet.ComputeRemainLaytime(Berthing_Date, dtLogIn.Rows(0).Item("Berthing_TimeTo"), dsBooking.Tables(0).Rows(0).Item("Lay_Time"), dsBooking.Tables(0).Rows(0).Item("Date_From"), dsBooking.Tables(0).Rows(0).Item("Date_To"), POB, POB_Time, Dis_Date & "", Dis_Time & "", NOR, NOR_Time)
                                    Else
                                        gridItem.Rows(i).Cells(28).Text = clsGet.ComputeRemainLaytime(Berthing_Date, dtLogIn.Rows(0).Item("Berthing_TimeTo"), dsBooking.Tables(0).Rows(0).Item("Lay_Time"), dsBooking.Tables(0).Rows(0).Item("Date_From"), dsBooking.Tables(0).Rows(0).Item("Date_To"), POB, POB_Time, "", "", NOR, NOR_Time)
                                    End If

                                Else
                                    Dim dtProductBulk As DataTable = clsGet.Get_Booking_Product(gridItem.DataKeys(i).Values("Booking_no"))
                                    If (dtProductBulk.Rows.Count > 0) Then
                                        Dim chkCoil As Boolean = False
                                        For Each dx As DataRow In dtProductBulk.Rows
                                            If (dx.Item("Group_no") & "" = "00007") Then
                                                chkCoil = True
                                                Exit For
                                            End If
                                        Next
                                        If (chkCoil) Then
                                            gridItem.Rows(i).Cells(28).Text = clsGet.ComputeRemainLaytimeBulk(dsBooking.Tables(0).Rows(0).Item("Lay_Time"), gridItem.DataKeys(i).Values("Booking_no"))
                                        End If
                                    End If
                                End If
                                If (gridItem.Rows(i).Cells(28).Text <> "") Then
                                    If (gridItem.Rows(i).Cells(28).Text.Substring(0, 1) = "-") Then
                                        gridItem.Rows(i).Cells(28).ForeColor = Drawing.Color.Red
                                    Else
                                        gridItem.Rows(i).Cells(28).ForeColor = Drawing.Color.Black
                                    End If
                                End If

                            End If
                        End If
                    End If
                End If
            End If
        Next
    End Sub

    Private Sub gridfile_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridfile.RowDataBound
        ' If (e.Row.RowType = DataControlRowType.DataRow) Then
        'Dim ImgDelete As ImageButton = CType(e.Row.FindControl("imgdelete"), ImageButton)
        'If (ViewState("EditBooking") & "" <> "") Then
        '    ImgDelete.Visible = False
        'End If
        ' End If
    End Sub

    Private Sub btnNew_Service_LOAD_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNew_Service_LOAD.Click
        ShowPanelForRole()
        ViewState("Load") = "Not"
        Timer1_Tick(sender, e)
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการบันทึกการขอเพิ่มบริการเรียบร้อย !!');", True)
    End Sub

    Private Sub btnAddNew_Service_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddNew_Service.Click
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_frameNew_Service').src = '../FormPopup/New_ServicePopup.aspx';", True)
        Session("Booking_NO_VALUE") = ViewState("EditBooking") & "$" & txtWater.Text
        ModalPopupExtenderService.Show()
    End Sub

    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "M")
        End If
    End Sub

    Private Sub btnSearchVPS_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchVPS.Click
        Dim ds As DataSet
        If (ddlStatusVPS.SelectedValue = "A") Then
            If (Session("Role") & "" = "00002") Or (Session("Role") & "" = "00007") Then
                'ลูกค้า
                ds = clsGet.Get_Booking(CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_Name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no") & "", "", "", False, ddlPORTVPS.SelectedValue.Replace("0", ""), txtShipVPS.Text, txtAGENTVPS.Text, "'CV','CC','CM','CR','CA'", txtBookingVPS.Text, "A", "", "", txtProductSearch.Text)
            Else
                ds = clsGet.Get_Booking(CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_Name"), "", "", "", True, ddlPORTVPS.SelectedValue.Replace("0", ""), txtShipVPS.Text, txtAGENTVPS.Text, "'CV','CC','CM','CR','CA'", txtBookingVPS.Text, "A", "", "", txtProductSearch.Text)
            End If
        Else
            If (Session("Role") & "" = "00002") Or (Session("Role") & "" = "00007") Then
                'ลูกค้า
                ds = clsGet.Get_Booking(CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_Name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no") & "", "", "'CV','CC','CM','CR','CA'", False, ddlPORTVPS.SelectedValue.Replace("0", ""), txtShipVPS.Text, txtAGENTVPS.Text, "", txtBookingVPS.Text, "A", "", "", txtProductSearch.Text)
            Else
                ds = clsGet.Get_Booking("", "", "", "'CV','CC','CM','CR','CA'", True, ddlPORTVPS.SelectedValue.Replace("0", ""), txtShipVPS.Text, txtAGENTVPS.Text, "", txtBookingVPS.Text, "A", "", "", txtProductSearch.Text)
            End If
        End If

        If (ds.Tables(0).Rows.Count > 0) Then
            ds.Tables(0).Columns.Add("Lay", GetType(String))
            ds.AcceptChanges()
            For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                ds.Tables(0).Rows(i).Item("Lay") = CDate(ds.Tables(0).Rows(i).Item("Date_From")).ToString("yyyyMMdd")
                ds.Tables(0).AcceptChanges()
            Next
            Dim dsView As DataView = ds.Tables(0).DefaultView
            dsView.Sort = " Lay DESC"
            ds = New DataSet
            ds.Tables.Add(clsGet.ConvertDataViewToDataSet(dsView).Copy)
            ViewState("Manage") = ds
            gridItem.DataSource = ViewState("Manage")
            gridItem.DataBind()
            ViewState("Load") = "Not"
            Timer1_Tick(sender, e)
        Else
            gridItem.DataSource = Nothing
            gridItem.DataBind()
        End If
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Application.Lock()
        conn.Open()
        Dim Booking As String = ""
        If (ViewState("EditBooking") & "" = "") Then
            Dim Pre_Booking As String = clsDB.GeneratorID(conn, "Pre_Booking")
            Booking = clsDB.GeneratorID(conn, "Booking")
            If (CInt(Pre_Booking) > CInt(Booking)) Then
                Booking = Pre_Booking
            End If
        Else
            Booking = ViewState("EditBooking")
        End If
        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
        Dim dsBooking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
        Dim Vehicle As String = ""
        Dim Vehicle_Name As String = ""
        Dim LOA As String = ""
        Dim DWT As String = ""
        Dim Draft As String = ""
        Dim GRT As String = ""
        Dim OwnerRequest As String = ""
        Dim CNTRY As String = ""
        Dim Vehicle_TypeBuy As String = ""
        Dim BunkerFO_chk As String = ""
        Dim BunkerDO_chk As String = ""
        Dim BunkerFO_Point As String = ""
        Dim BunkerDO_Point As String = ""

        Dim dsProduct As DataTable = Session("Product_popup")
        Dim ProductName As String = ""
        Dim ProductAmount As Double = 0.0
        Dim ProductAmountByLine As String = ""
        Dim ProductAmountByProduct As String = ""
        Dim ProductType As String = ""
        Dim ProductBuyer As String = ""
        Dim ProductSeller As String = ""
        For Each dr As DataRow In dsProduct.Rows
            If (dr.Item("Product_name") & "" <> "") Then
                ProductName &= "," & dr.Item("Product_name")
                ProductAmountByLine &= "," & dr.Item("Product_Amount")
                ProductAmount = ProductAmount + (CDbl(dr.Item("Product_Amount")))
                ProductType &= "," & dr.Item("Product_Unit")
                ProductBuyer &= "," & dr.Item("Product_BUYER_name")
                ProductSeller &= "," & dr.Item("Product_SELLER_name")
                ProductAmountByProduct &= dr.Item("Product_name") & "฿" & dr.Item("Product_Amount") & "฿"
            End If
        Next
        If (ProductName.Length > 0) Then
            ProductName = ProductName.Substring(1, ProductName.Length - 1)
            ProductAmountByLine = ProductAmountByLine.Substring(1, ProductAmountByLine.Length - 1)
            ProductType = ProductType.Substring(1, ProductType.Length - 1)
            ProductBuyer = ProductBuyer.Substring(1, ProductBuyer.Length - 1)
            ProductSeller = ProductSeller.Substring(1, ProductSeller.Length - 1)
        End If

        ViewState("Product_NameAmount") = ProductName & "$" & ProductAmount & "$" & ProductType & "$" & ProductBuyer & "$" & ProductSeller
        Dim Product_Name As String = ViewState("Product_NameAmount").ToString().Split("$")(0)
        If (chkFO.Checked) Then
            BunkerFO_chk = "Y"
            BunkerFO_Point = txtFO.Text.Trim()
            If (Product_Name.Trim <> "") Then
                Product_Name &= ",BunkerFO " & BunkerFO_Point & " คัน"
            Else
                Product_Name &= "BunkerFO " & BunkerFO_Point & " คัน"
            End If
        Else
            BunkerFO_chk = "N"
            BunkerFO_Point = "0"
        End If

        'If (lbFT1.Text = "FT") Then
        '    If (txtLOA.Text.Trim() <> "") Then
        '        Try
        '            txtLOA.Text = (CDbl(txtLOA.Text) * 3.281).ToString("############0.00")
        '        Catch ex As Exception

        '        End Try
        '    End If
        '    If (txtDraft.Text.Trim() <> "") Then
        '        Try
        '            txtDraft.Text = (CDbl(txtDraft.Text) * 3.281).ToString("############0.00")
        '        Catch ex As Exception

        '        End Try
        '    End If
        'End If

        If (chkDO.Checked) Then
            BunkerDO_chk = "Y"
            BunkerDO_Point = txtDO.Text.Trim()
            If (Product_Name.Trim <> "") Then
                Product_Name &= ",BunkerDO " & BunkerDO_Point & " คัน"
            Else
                Product_Name &= "BunkerDO " & BunkerDO_Point & " คัน"
            End If
        Else
            BunkerDO_chk = "N"
            BunkerDO_Point = "0"
        End If

        Dim File_Upload As String = ""
        Dim dt As DataTable = Session("Q88")
        For Each dr As DataRow In dt.Rows
            'File_Upload = File_Upload.Replace("," & dr.Item("File_Type"), "")
            'File_Upload &= "," & dr.Item("File_Type")
            File_Upload &= "," & dr.Item("File_name")
        Next
        If (File_Upload.Length > 0) Then
            File_Upload = File_Upload.Substring(1, File_Upload.Length - 1)
        End If

        Dim MAgent_no As String = ""
        Dim MAgent_name As String = ""
        Dim SAgent_name As String = ""
        Dim SAgent_no As String = ""
        If (txtid.Text.Trim = "") Then
            MAgent_no = ""
            MAgent_name = ""
        Else
            MAgent_no = txtid.Text.Split("-")(0)
            ' MAgent_name = txtid.Text.Split("-")(1)
            Dim AgentLoops() As String = txtid.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    MAgent_name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            MAgent_name = MAgent_name.Substring(1, MAgent_name.Length - 1)
        End If
        If (txtAgent.Text.Trim = "") Then
            SAgent_no = ""
            SAgent_name = ""
        Else
            SAgent_no = txtAgent.Text.Split("-")(0)
            'SAgent_name = txtAgent.Text.Split("-")(1)
            Dim AgentLoops() As String = txtAgent.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    SAgent_name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            SAgent_name = SAgent_name.Substring(1, SAgent_name.Length - 1)
        End If
        If (raioType.SelectedValue = "O") Then
            Vehicle_TypeBuy = radioTypeBuy.SelectedValue
        End If
        If (Session("Role") & "" = "00002") Then
            OwnerRequest = ""
        Else
            OwnerRequest = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name")
        End If
        Dim standardTime As String = ""
        If (Session("Lay_Time") & "" = "") Then
            standardTime = "0"
        Else
            standardTime = Session("Lay_Time") & ""
        End If
        If (radioVehicle.SelectedValue = "0") Then
            Vehicle = txtVessel.Text.Split("-")(0)
            '  Vehicle_Name = txtVessel.Text.Split("-")(1)
            Dim AgentLoops() As String = txtVessel.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    Vehicle_Name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            Vehicle_Name = Vehicle_Name.Substring(1, Vehicle_Name.Length - 1)
            LOA = lbLOA.Text.Trim()
            DWT = lbDWT.Text.Trim()
            Draft = lbDraft.Text.Trim()
            GRT = lbGRT.Text.Trim()
            CNTRY = lbNation.Text.Trim()
        Else
            Vehicle = "999999999"
            Vehicle_Name = txtVesselOUT.Text.Trim()
            LOA = txtLOA.Text.Trim()
            DWT = txtDWT.Text.Trim()
            Draft = txtDraft.Text.Trim()
            GRT = txtGRT.Text.Trim()
            CNTRY = ddlNation.SelectedValue.Replace("T", "TH")
        End If
        Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
        Dim Vps_Approve As String = ""
        Dim Vps_Remark As String = ""
        Dim MRI_APprove As String = ""
        Dim MRI_Remark As String = ""
        Dim Marketing_approve As String = ""
        Dim Payin As String = ""
        Dim Credit_limit As String = ""
        Dim Bill_to_no As String = ""
        Dim Bill_to_name As String = ""
        Dim MKT_Approve As String = ""
        Dim Cancel_By As String = ""
        Dim Cancel_Description As String = ""
        Dim VPS_Ac As String = ""
        Dim MKT_Ac As String = ""
        If (ds_Log.Rows.Count > 0) Then
            Vps_Approve = ds_Log.Rows(0).Item("VPS_approve") & ""
            Vps_Remark = ds_Log.Rows(0).Item("Remark_VPS") & ""
            MRI_APprove = ds_Log.Rows(0).Item("MRI_approve") & ""
            MRI_Remark = ds_Log.Rows(0).Item("Remark_MRI") & ""
            Marketing_approve = ds_Log.Rows(0).Item("Marketing_approve") & ""
            Payin = ds_Log.Rows(0).Item("Payin") & ""
            Credit_limit = ds_Log.Rows(0).Item("Credit_Limit") & ""
            Bill_to_no = ds_Log.Rows(0).Item("Bill_To_no") & ""
            Bill_to_name = ds_Log.Rows(0).Item("Bill_To_name") & ""
            MKT_Approve = ds_Log.Rows(0).Item("MKT_Approve") & ""
            Cancel_By = ds_Log.Rows(0).Item("Cancel_By") & ""
            Cancel_Description = ds_Log.Rows(0).Item("Cancel_Description") & ""
            VPS_Ac = ds_Log.Rows(0).Item("Vps_Acknowledge") & ""
            MKT_Ac = ds_Log.Rows(0).Item("MKT_Acknowledge") & ""
        End If
        Dim shifting As String = ""
        Dim ProductText As String = ""
        tran = clsDB.BeginTran(conn)
        Try
            If (clsFc.InsertBooking(ViewState("EditBooking"), Booking, hdfUsername.Value, txtName.Text, Vehicle, Vehicle_Name, LOA, DWT, Draft, GRT, txtDate.Text, txtDateTo.Text, radioPort.SelectedValue, raioType.SelectedValue, Vehicle_TypeBuy, txtRemark.Text, ViewState("ST"), Vps_Remark, Vps_Approve, MRI_Remark, MRI_APprove, Marketing_approve, Product_Name, ViewState("Product_NameAmount").ToString().Split("$")(1), MAgent_no, MAgent_name, SAgent_no, SAgent_name, txtDateBooking.Text, txtTimeBooking.Text, ViewState("Product_NameAmount").ToString().Split("$")(3), ViewState("Product_NameAmount").ToString().Split("$")(4), ViewState("Product_NameAmount").ToString().Split("$")(2), File_Upload, CNTRY, txtLayTime.Text.Trim(), "N", "N", "N", BunkerFO_chk, BunkerDO_chk, BunkerFO_Point, BunkerDO_Point, txtBunkerDetail.Text, txtWater.Text.Trim(), Payin, standardTime, Credit_limit, txtDemurrage.Text, ddlDemurrage.SelectedValue, txtElectricity.Text, shifting, conn, tran) > 0) Then
                If (clsFc.InsertBooking_Log(Booking_Log, Booking, hdfUsername.Value, txtName.Text, Vehicle, Vehicle_Name, LOA, DWT, Draft, GRT, txtDate.Text, txtDateTo.Text, radioPort.SelectedValue, raioType.SelectedValue, Vehicle_TypeBuy, txtRemark.Text, ViewState("ST"), Vps_Remark, Vps_Approve, MRI_Remark, MRI_APprove, Marketing_approve, Product_Name, ViewState("Product_NameAmount").ToString().Split("$")(1), MAgent_no, MAgent_name, SAgent_no, SAgent_name, txtDateBooking.Text, txtTimeBooking.Text, ViewState("Product_NameAmount").ToString().Split("$")(3), ViewState("Product_NameAmount").ToString().Split("$")(4), ViewState("Product_NameAmount").ToString().Split("$")(2), File_Upload, CNTRY, txtLayTime.Text, "N", "N", "N", BunkerFO_chk, BunkerDO_chk, BunkerFO_Point, BunkerDO_Point, txtBunkerDetail.Text, txtWater.Text.Trim(), MKT_Approve, Cancel_By, Cancel_Description, VPS_Ac, MKT_Ac, Payin, Bill_to_no, Bill_to_name, standardTime, Credit_limit, "N", txtDemurrage.Text, ddlDemurrage.SelectedValue, txtElectricity.Text, shifting, conn, tran) > 0) Then

                    ' clsFc.DeleteBookingProduct(Booking, conn, tran)
                    Dim AllProduct As String = "''"
                    For Each dr As DataRow In dsProduct.Rows
                        If (dr.Item("Product_no") & "" <> "") Then
                            Dim Destination As String = ""
                            If (dr.Item("Product_Event") = "L") Or (dr.Item("Product_Event") = "R") Then
                                Destination = dr.Item("LoadDestination")
                            Else
                                Destination = dr.Item("DischDestination")
                            End If
                            If (clsFc.InsertBooking_Product("EDIT", Booking, dr.Item("Product_no"), dr.Item("Product_name"), dr.Item("Product_Amount"), dr.Item("Product_Event"), dr.Item("Group_no"), dr.Item("Group_name"), dr.Item("Product_Buyer_no"), dr.Item("Product_Buyer_name"), dr.Item("Product_Seller_no"), dr.Item("Product_Seller_name"), dr.Item("LoadDestination"), dr.Item("DischDestination"), dr.Item("DestinationShow"), dr.Item("Product_Description"), dr.Item("Product_Unit"), dr.Item("Owner_Product_no"), dr.Item("Owner_Product_name"), conn, tran) < 1) Then
                                If (clsFc.InsertBooking_Product("", Booking, dr.Item("Product_no"), dr.Item("Product_name"), dr.Item("Product_Amount"), dr.Item("Product_Event"), dr.Item("Group_no"), dr.Item("Group_name"), dr.Item("Product_Buyer_no"), dr.Item("Product_Buyer_name"), dr.Item("Product_Seller_no"), dr.Item("Product_Seller_name"), dr.Item("LoadDestination"), dr.Item("DischDestination"), dr.Item("DestinationShow"), dr.Item("Product_Description"), dr.Item("Product_Unit"), dr.Item("Owner_Product_no"), dr.Item("Owner_Product_name"), conn, tran) < 1) Then
                                    condition = False
                                    Exit For
                                Else
                                    AllProduct &= ",'" & dr.Item("Product_no") & "'"
                                End If
                            Else
                                AllProduct &= ",'" & dr.Item("Product_no") & "'"
                            End If
                        End If
                    Next
                    clsFc.DeleteBookingProduct(Booking, AllProduct, conn, tran)
                    'Else
                    '   ProductText = "<br />ไม่สามาทำการแก้ไขข้อมูล Product ได้"
                    ' End If


                    clsFc.DeleteBooking_Upload(Booking, conn, tran)
                    For Each dr As DataRow In dt.Rows
                        If (clsFc.InsertBooking_Upload(Booking, dr.Item("File_nameGuid"), dr.Item("File_name"), dr.Item("File_type"), dr.Item("File_ContentType"), dr.Item("Upload_Type"), dr.Item("Description"), conn, tran) < 1) Then
                            condition = False
                            Exit For
                        End If
                    Next

                Else
                    condition = False
                End If
            Else
                condition = False
            End If
            If (condition) Then
                clsDB.CommitTran(tran)
                If (SendMail(GenBody("รายการจองได้ถูกทำการแก้ไขข้อมูลกรุณาทำการตรวจสอบข้อมูล", ViewState("EditBooking"), MAgent_no & "-" & MAgent_name, Vehicle & "-" & Vehicle_Name, txtDate.Text & "-" & txtDateTo.Text))) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ " & ProductText & " !!');", True)
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ " & ProductText & " !!');", True)
                End If

                Session("Product_popup") = CreateDatasetProduct()
                Session("Lay_Time") = "0"

                Session("MAT_USE") = ""
                Session("Value") = Nothing
                Session("Q88") = CreateFileDataTable()
                Session("StandardTimePlus") = 0
                ViewState("Status") = ""
                Session("Operation") = Nothing
                PanelBookingItem.Visible = True
                PanelBooking.Visible = False
                ClearData()
                ShowPanelForRole()
                ViewState("Load") = "Not"
                Timer1_Tick(sender, e)

                ViewState("EditBooking") = ""
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก !!');", True)
            End If
        Catch ex As Exception
            clsDB.RollBackTran(tran)
            'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & ex.Message & "');", True)
            txtRemark.Text = ex.Message
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก  !!');", True)
        End Try
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Function GenBody(ByVal str As String, ByVal booking_no As String, ByVal Agent As String, ByVal Vessel As String, ByVal Laycan As String) As String
        Dim HTML As String = ""
        HTML = "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td align='left'><font class='White-Style' font-weight:bold style='color:#000000'>" & str & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"
        HTML &= "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Booking No. :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & booking_no & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Sold To :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Agent & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Vessel :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Vessel & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Lay Can\Lay Day :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Laycan & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"
        Return HTML
    End Function

    Private Function SendMail(ByVal Body As String) As Boolean
        Dim test As String = clsFc.sendmail(clsGet.Get_EmailForSend("'00003','00004'"), "", "iPORT", Body, "")
        If (test <> "") Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub btnTariff_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTariff.Click
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_framePopup').src = '../FormPopup/FrmTariff_Popup.aspx';", True)
        ModalPopupExtender1.Show()
    End Sub

    Private Sub btnCancelBooking_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelBooking.Click
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_CancelPopup').src = '../FormPopup/Cancel_popup.aspx';", True)
        ModalPopupExtender6.Show()
    End Sub
    Private Sub CopyBooking()
        PanelBooking.Visible = True
        PanelBookingItem.Visible = False
        PanelVessel.Visible = True
        lbFT1.Text = "FT"
        lbFT2.Text = "FT"
        ViewState("EditBooking") = "" '*********************************
        Dim rowEditIndex As Integer = CType(ViewState("rowEditIndex"), Integer)
        Dim admin As Boolean = True
        If (Session("Role") = "00002") Then
            admin = False
        End If
        Dim dsBooking As DataSet = CType(ViewState("BookingDataset"), DataSet) 'clsGet.Get_Booking(CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_Name"), gridItem.DataKeys(rowEditIndex).Values("Customer_no") & "", gridItem.DataKeys(rowEditIndex).Values("Booking_no"), "", admin, "", "", "", "", "", "A", "", "", "") '*********************************************
        If (Session("Role") & "" = "00002") Then
            rowGridTariff.Visible = False
        Else
            rowGridTariff.Visible = True
        End If
        btnCancelBooking.Visible = False
        btnUpdate.Visible = False
        btnAddNew_Service.Visible = False
        btnCompute.Text = "BOOKING"
        btnCompute.Visible = False
        rowCancel.Visible = False
        rowGridTariff.Visible = False
        UpdatePanelTariff.Visible = True
        btnComputeTariff.Visible = True
        PanelDetail.Visible = True
        ViewState("ST") = gridItem.DataKeys(rowEditIndex).Values("Status") & "" '*********************************************
        If (gridItem.DataKeys(rowEditIndex).Values("Status") & "" <> "NB") Then '************************************
            ViewState("Status") = "NOT_NEW"
            txtVessel.Enabled = False
            txtVesselOUT.Enabled = False
            btnTariff.Visible = False
            btnSearch.Visible = False
            btnSearchOUT.Visible = False
            radioPort.Enabled = False
            radioVehicle.Enabled = False
        Else
            ViewState("Status") = ""
            txtVessel.Enabled = True
            txtVesselOUT.Enabled = True
            btnTariff.Visible = True
            btnSearch.Visible = True
            btnSearchOUT.Visible = True
            radioPort.Enabled = True
            radioVehicle.Enabled = True
        End If
        ' btnAddNew_Service.Visible = True
        'btnCompute.Text = "แสดงค่าประมาณการ"
        rowDetailAll.Visible = True
        If (gridItem.DataKeys(rowEditIndex).Values("MAgent_no") & "" <> "") Then '*********************************************
            txtid.Text = gridItem.DataKeys(rowEditIndex).Values("MAgent_no") & "-" & gridItem.DataKeys(rowEditIndex).Values("MAgent_name") '*********************************************
        Else
            txtid.Text = String.Empty
        End If
        If (gridItem.DataKeys(rowEditIndex).Values("SAgent_no") & "" <> "") Then '*********************************************
            txtAgent.Text = gridItem.DataKeys(rowEditIndex).Values("SAgent_no") & "-" & gridItem.DataKeys(rowEditIndex).Values("SAgent_name") '*********************************************
        Else
            txtAgent.Text = String.Empty
        End If

        radioVehicle.ClearSelection()


        'Try
        '    txtName.Text = dsBooking.Tables(0).Rows(0).Item("Booking_Name")
        '    hdfUsername.Value = dsBooking.Tables(0).Rows(0).Item("Booking_Code")
        'Catch ex As Exception

        'End Try

        'Session("MAT_USE") = clsGet.Get_BookingTariff(gridItem.DataKeys(rowEditIndex).Values("Booking_no"), "") '*********************************************
        'Session("Product_popup") = clsGet.Get_Booking_Product(gridItem.DataKeys(rowEditIndex).Values("Booking_no")) '*********************************************
        'Session("Q88") = clsGet.Get_BookingUpload(gridItem.DataKeys(rowEditIndex).Values("Booking_no")) '*********************************************

        'Select Case dsBooking.Tables(0).Rows(0).Item("Status")
        '    Case "CC"
        '        lbCancel.Text = "ลูกค้าประสงค์ทำการยกเลิก รอการยืนยันจากทาง VPS<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
        '        If (dsBooking.Tables(0).Rows(0).Item("Vps_Acknowledge") & "" <> "") Then
        '            lbCancel.Text &= "<br /> VPS รับทราบการขอยกเลิกรายการจองแล้ว"
        '            btnCancel.Visible = False
        '        End If
        '        If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
        '            lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
        '            btnCancel.Visible = False
        '        End If
        '    Case "CR"
        '        lbCancel.Text = "ยกเลิกโดย MRI<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
        '        btnCancel.Visible = False
        '        If (dsBooking.Tables(0).Rows(0).Item("Vps_Acknowledge") & "" <> "") Then
        '            lbCancel.Text &= "<br /> VPS รับทราบการขอยกเลิกรายการจองแล้ว"
        '        End If
        '        If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
        '            lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
        '        End If
        '    Case "CM"
        '        lbCancel.Text = "ยกเลิกโดย Marketing<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
        '        btnCancel.Visible = False
        '        If (dsBooking.Tables(0).Rows(0).Item("Vps_Acknowledge") & "" <> "") Then
        '            lbCancel.Text &= "<br /> VPS รับทราบการขอยกเลิกรายการจองแล้ว"
        '        End If
        '    Case "CV"
        '        lbCancel.Text = "ยกเลิกโดย VPS<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
        '        btnCancel.Visible = False
        '        If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
        '            lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
        '        End If
        '    Case "CA"
        '        lbCancel.Text = "ยกเลิกโดย VPS ตามคำร้องขอ ของลูกค้า<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
        '        btnCancel.Visible = False
        '        If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
        '            lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
        '        End If
        'End Select
        Dim Load As String = ""
        Dim Disch As String = ""
        Dim LoadIRPC As String = ""
        Dim DischIRPC As String = ""
        For Each dr As DataRow In CType(Session("Product_popup"), DataTable).Rows
            Select Case dr.Item("Product_Event") & ""
                Case "L" : Load = "Y"
                Case "D" : Disch = "Y"
                Case "R" : LoadIRPC = "Y"
                Case "I" : LoadIRPC = "Y"
            End Select
            If (dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination") = "O") Then
                Session("Operation") = Load & "$" & Disch & "$" & LoadIRPC & "$" & DischIRPC & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination") & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy")
            Else
                Session("Operation") = Load & "$" & Disch & "$" & LoadIRPC & "$" & DischIRPC & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination") & "$" & ""
            End If
        Next
        Dim RemarkVPS As String = ""
        Dim FirstRemarkVPS As Boolean = True
        Dim TimeCreateRemark As String = ""
        Dim dsRemark As DataTable = clsGet.Get_Booking_LogRemarkVPS(gridItem.DataKeys(rowEditIndex).Values("Booking_no"), "VPS") '************************
        If (dsRemark.Rows.Count > 0) Then
            rowRemarkVPS.Visible = True
            For Each drVPS As DataRow In dsRemark.Rows
                If (drVPS.Item("Remark_VPS") & "" <> "") Then
                    TimeCreateRemark = drVPS.Item("Booking_log")
                    If (FirstRemarkVPS) Then
                        RemarkVPS = TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_VPS")
                        FirstRemarkVPS = False
                    Else
                        RemarkVPS &= "<BR />" & TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_VPS")
                    End If
                End If
            Next
            If (RemarkVPS.Trim() = "") Then
                lbRemark_VPS.Text = String.Empty
                rowRemarkVPS.Visible = False
            Else
                lbRemark_VPS.Text = RemarkVPS
            End If
        Else
            lbRemark_VPS.Text = String.Empty
            rowRemarkVPS.Visible = False
        End If


        Dim RemarkMRI As String = ""
        Dim FirstRemarkMRI As Boolean = True
        TimeCreateRemark = ""
        dsRemark = clsGet.Get_Booking_LogRemarkVPS(gridItem.DataKeys(rowEditIndex).Values("Booking_no"), "MRI") '*****************************
        If (dsRemark.Rows.Count > 0) Then
            rowRemarkMRI.Visible = True
            For Each drVPS As DataRow In dsRemark.Rows
                If (drVPS.Item("Remark_MRI") & "" <> "") Then
                    TimeCreateRemark = drVPS.Item("Booking_log")
                    If (FirstRemarkMRI) Then
                        RemarkMRI = TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_MRI")
                        FirstRemarkMRI = False
                    Else
                        RemarkMRI &= "<BR />" & TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_MRI")
                    End If
                End If
            Next
            If (RemarkMRI.Trim() = "") Then
                lbRemark_MRI.Text = String.Empty
                rowRemarkMRI.Visible = False
            Else
                lbRemark_MRI.Text = RemarkMRI
            End If
        Else
            lbRemark_MRI.Text = String.Empty
            rowRemarkMRI.Visible = False
        End If
        Try
            If (CType(Session("Product_popup"), DataTable).Rows.Count = 0) Then
                Session("Product_popup") = CreateDatasetProduct()
            End If
        Catch ex As Exception

        End Try
        If (dsBooking.Tables(0).Rows(0).Item("PORT") = "B") Then
            SetProductBulk(Session("Product_popup"))
        End If
        gridProduct.PageIndex = 0
        gridProduct.DataSource = Session("Product_popup")
        gridProduct.DataBind()
        gridTariff.PageIndex = 0
        gridTariff.DataSource = Session("MAT_USE")
        gridTariff.DataBind()
        gridfile.PageIndex = 0
        gridfile.DataSource = Session("Q88")
        gridfile.DataBind()
        'ComputeTariff.Visible = False
        If (dsBooking.Tables(0).Rows.Count = 1) Then
            If (gridItem.DataKeys(rowEditIndex).Values("Vehicle_no") & "" = "999999999") Then '*********************************************
                radioVehicle.SelectedValue = "1"
                PanelVEHICLE_OUT.Visible = True
                PanelVEHICLE_IN.Visible = False
                PanelVEHICLE_IN_DETAIL.Visible = False
                txtVesselOUT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
                txtLOA.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_LOA")
                txtDWT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_DWT").ToString().Trim()
                txtDraft.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_Draft")
                txtGRT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_GRT")
                If Not (ddlNation.Items.FindByValue(dsBooking.Tables(0).Rows(0).Item("Vehicle_CNTRY").ToString().Replace("TH", "T")) Is Nothing) Then
                    ddlNation.SelectedValue = dsBooking.Tables(0).Rows(0).Item("Vehicle_CNTRY").ToString().Replace("TH", "T")
                Else
                    ddlNation.SelectedValue = "O"
                End If
            Else
                radioVehicle.SelectedValue = "0"
                PanelVEHICLE_IN.Visible = True
                PanelVEHICLE_IN_DETAIL.Visible = True
                PanelVEHICLE_OUT.Visible = False
                txtVessel.Text = gridItem.DataKeys(rowEditIndex).Values("Vehicle_no") & "-" & gridItem.DataKeys(rowEditIndex).Values("Vehicle_Text") '*********************************************

                Dim ds As DataTable = clsGet.Get_VEHICLE_DETAIL(gridItem.DataKeys(rowEditIndex).Values("Vehicle_no"))
                ' If (UpdateVessel(gridItem.DataKeys(rowEditIndex).Values("Vehicle_no"))) Then
                'ds = clsGet.Get_VEHICLE_DETAIL(gridItem.DataKeys(rowEditIndex).Values("Vehicle_no"))
                lbLOA.Text = (CDbl(ds.Rows(0).Item("VEH_LENGTH")) * 3.281).ToString("############0.00")
                lbDWT.Text = ds.Rows(0).Item("VEH_MAXWGT_C").ToString().Trim()
                lbDraft.Text = (CDbl(ds.Rows(0).Item("DRAFT")) * 3.281).ToString("############0.00")
                lbNation.Text = ds.Rows(0).Item("REG_CNTRY")
                If Not ((ds.Rows(0).Item("STCMNR") & "").ToString().Trim() = "") Then
                    Try
                        lbGRT.Text = ds.Rows(0).Item("STCMNR").ToString().Replace("GRT", "").Replace("=", "").Replace("MT", "")
                    Catch ex As Exception

                    End Try
                End If
                'End If
                'lbLOA.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_LOA")
                'lbDWT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_DWT").ToString().Trim()
                'lbDraft.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_Draft")
                'lbGRT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_GRT")
                'lbNation.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_CNTRY")
            End If
            txtDate.Text = ""
            txtDate.BackColor = Drawing.Color.Red
            txtDateTo.Text = ""
            txtDateTo.BackColor = Drawing.Color.Red
            txtDateBooking.Text = ""
            txtTimeBooking.Text = ""



            If ((dsBooking.Tables(0).Rows(0).Item("Lay_Time") & "" <> "0") And (dsBooking.Tables(0).Rows(0).Item("Lay_Time") & "" <> "")) Or ((dsBooking.Tables(0).Rows(0).Item("Demurrage") & "" = "0") And (dsBooking.Tables(0).Rows(0).Item("Demurrage") & "" = "")) Then
                radioDemurrage.ClearSelection()
                radioDemurrage.SelectedValue = "Y"
                rowLaytime.Visible = True

                txtLayTime.Text = dsBooking.Tables(0).Rows(0).Item("Lay_Time")
                txtDemurrage.Text = dsBooking.Tables(0).Rows(0).Item("Demurrage")
                If Not (ddlDemurrage.Items.FindByValue(dsBooking.Tables(0).Rows(0).Item("Demurrage_Money") & "") Is Nothing) Then
                    ddlDemurrage.SelectedValue = dsBooking.Tables(0).Rows(0).Item("Demurrage_Money") & ""
                End If
            Else
                txtLayTime.Text = "0"
                txtDemurrage.Text = "0"
                radioDemurrage.ClearSelection()
                radioDemurrage.SelectedValue = "N"
                rowLaytime.Visible = False
            End If

            txtWater.Text = dsBooking.Tables(0).Rows(0).Item("Water_Point")
            If (dsBooking.Tables(0).Rows(0).Item("BunkerFO_chk") & "" = "Y") Then
                chkFO.Checked = True
                txtFO.Text = dsBooking.Tables(0).Rows(0).Item("BunkerFO_Point") & ""
            Else
                txtFO.Text = "0"
            End If
            If (dsBooking.Tables(0).Rows(0).Item("BunkerDO_chk") & "" = "Y") Then
                chkDO.Checked = True
                txtDO.Text = dsBooking.Tables(0).Rows(0).Item("BunkerDO_Point") & ""
            Else
                txtDO.Text = "0"
            End If
            Dim vehDest As String
            Try
                vehDest = dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination").ToString()
            Catch ex As Exception
                vehDest = ""
            End Try
            If Not (raioType.Items.FindByValue(vehDest) Is Nothing) Then
                raioType.SelectedValue = vehDest
                Dim vehTypeBuy As String = dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy").ToString()
                If vehDest = "O" Then

                    If vehTypeBuy <> "" Then
                        radioTypeBuy.SelectedValue = dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy")
                    End If
                    rowTypeBuy.Visible = True

                End If

                'If (radioTypeBuy.SelectedValue = "O") Then
                '    rowTypeBuy.Visible = True
                '    If Not (radioTypeBuy.Items.FindByValue(dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy")) Is Nothing) Then
                '        radioTypeBuy.SelectedValue = dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy")
                '    End If
                'End If
            End If
            If Not (radioPort.Items.FindByValue(dsBooking.Tables(0).Rows(0).Item("PORT")) Is Nothing) Then
                radioPort.SelectedValue = dsBooking.Tables(0).Rows(0).Item("PORT")
            End If
            txtRemark.Text = dsBooking.Tables(0).Rows(0).Item("Remark")
        End If
        'If ((ViewState("ST") & "" = "OA") Or (ViewState("ST") & "" = "FN")) Then
        '    btnCompute.Visible = False
        '    btnUpdate.Visible = False
        'ElseIf ((ViewState("ST") & "" = "CC") Or (ViewState("ST") & "" = "CA") Or (ViewState("ST") & "" = "CV") Or (ViewState("ST") & "" = "CM") Or (ViewState("ST") & "" = "CR")) Then
        '    btnCompute.Visible = False
        '    btnCancelBooking.Visible = False
        '    rowCancel.Visible = True
        '    btnUpdate.Visible = False
        'Else
        '    btnCompute.Visible = False
        '    btnUpdate.Visible = True
        'End If
        If (dsBooking.Tables(0).Rows(0).Item("Marketing_approve") & "" = "") And (dsBooking.Tables(0).Rows(0).Item("VPS_approve") & "" = "") Then
            If PanelVEHICLE_IN.Visible Then
                btnSearch.Visible = True
                txtVessel.Enabled = True
            Else
                btnSearchOUT.Visible = True
                txtVesselOUT.Enabled = True
                txtLOA.Enabled = True
                txtGRT.Enabled = True
                txtDWT.Enabled = True
                txtDraft.Enabled = True
                ddlNation.Enabled = True
            End If

        Else
            If PanelVEHICLE_IN.Visible Then
                btnSearch.Visible = False
                txtVessel.Enabled = False
            Else
                btnSearchOUT.Visible = False
                txtVesselOUT.Enabled = False
                txtLOA.Enabled = False
                txtGRT.Enabled = False
                txtDWT.Enabled = False
                txtDraft.Enabled = False
                ddlNation.Enabled = False
            End If
        End If

    End Sub
    Private Sub btnCopyBooking_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCopyBooking.Click
        btnCopyBooking.Visible = False
        btnCompute.Visible = True
        btnUpdate.Visible = False
        PanelBooking.Visible = True
        PanelBookingItem.Visible = False
        PanelDetail.Visible = False
        radioPort.ClearSelection()
        radioPort.Enabled = True
        txtAgent.Enabled = True
        txtAgent.Text = String.Empty
        btnProduct.Enabled = True
        btnProduct.Visible = True
        txtid.Enabled = True
        txtVessel.Enabled = True
        txtVesselOUT.Enabled = True
        ddlNation.Enabled = True
        txtLOA.Enabled = True
        txtDraft.Enabled = True
        txtDWT.Enabled = True
        txtGRT.Enabled = True
        btnSearchOUT.Visible = True
        btnSearch.Visible = True
        btnAddNew_Service.Visible = False
        rowDetailAll.Visible = False
        PanelDetail.Visible = False
        PanelVessel.Visible = True '************************************
        PanelVEHICLE_IN_DETAIL.Visible = True '*************************************
        'ViewState("Status") = ""
        ' Session("Product_popup") = CreateDatasetProduct()
        ViewState("EditBooking") = ""
        'Session("Lay_Time") = "0"

        ' Session("MAT_USE") = ""
        ' Session("Value") = Nothing
        'Session("Q88") = CreateFileDataTable()
        gridfile.DataSource = Session("Q88")
        gridfile.DataBind()
        ' Session("StandardTimePlus") = 0
        
        'Session("Operation") = Nothing

        gridProduct.DataSource = Session("Product_popup")
        gridProduct.DataBind()
        txtDate.Enabled = True
        ImgDate.Enabled = True
        txtDateTo.Enabled = True
        ImgDateTo.Enabled = True
        ImgDateBooking.Enabled = True
        txtDateBooking.Enabled = True
        txtTimeBooking.Enabled = True
        ClearData()
        txtName.Text = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name")
        hdfUsername.Value = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name")
        btnCompute.Visible = False
        btnCancelBooking.Visible = False
        If (Session("Role") <> "00002") Then
            ComputeTariff.Visible = True
            rowGridTariff.Visible = False
        Else
            ComputeTariff.Visible = False
            rowGridTariff.Visible = False
        End If
        CopyBooking()
    End Sub

    
    Protected Sub btnViewChildBooking_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnViewChildBooking.Click
        Dim comArg As String = btnViewChildBooking.CommandArgument
        Dim splitComArg As String() = comArg.Split(";")
        Dim rowEdit As Integer = CType(ViewState("rowEditIndex"), Integer)
        Dim booking_no As String = splitComArg(1)
        GetEditGridItem(booking_no,rowEdit)
    End Sub
End Class
